Matrix Output Matlab Calculation

Click For Summary
SUMMARY

The discussion focuses on generating a matrix output in MATLAB using a custom function to calculate values based on two input parameters, 'a' and 'b'. The original script failed to produce all combinations of 'i' and 'j' values, resulting in incomplete calculations for 'k'. A revised approach utilizing nested for loops effectively iterates through all combinations, ensuring that every 'j' value is matched with each 'i' value before calculating 'k'. This method guarantees a comprehensive matrix output.

PREREQUISITES
  • Understanding of MATLAB programming and syntax
  • Familiarity with matrix operations in MATLAB
  • Knowledge of nested loops in programming
  • Basic mathematical operations involving arrays
NEXT STEPS
  • Explore MATLAB's array manipulation functions
  • Learn about MATLAB's for loop and its applications
  • Investigate MATLAB's matrix indexing techniques
  • Study advanced MATLAB functions for performance optimization
USEFUL FOR

MATLAB programmers, data analysts, and anyone involved in mathematical modeling or matrix computations in MATLAB.

Air
Messages
202
Reaction score
0
I am making a script-m file to produce results of a formula in a Matrix output.

Code:
function s = calc(a, b)

i = [-a: 1: a];
j = [-b: 1: b];

k = i.^2 + j.*i;

A = [i' j' k']

disp('i  j  k'), disp(A)

But, it does not consider all combination. How can I make it stop at a 'i' value so all 'j' values can be matched to that and solved for 'k' before proceeding. In my code, it just does one round of 'i' and 'j' values.
 
Physics news on Phys.org
I'm not sure I understand the question...

If you want to create a matrix k that contains every combination of the i and j values, then you might try something like:

Code:
function s = calc(a, b)

i = [-a: 1: a];
j = [-b: 1: b];

%  Use an outer for loop to iterate through all of the i values (uses index u)
for u = 1:1:max(size(i))
    %  Use an inner for loop to iterate through all of the j values (uses index v)
    for v = 1:1:max(size(j))
        %  Here we construct k to have two dimensions, the first corresponding to
        %  the i value, the second corresponding to the j value
        k(u, v) = i(u)^2 + j(v) * i(u);
    end
end

%  If i and j are different lengths, MATLAB won't let you do this...
A = [i' j' k']

disp('i  j  k'), disp(A)

Hope this helps,

Kerry
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
5
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
4K
  • · Replies 32 ·
2
Replies
32
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 6 ·
Replies
6
Views
2K