MATLAB Building a matrix using while loops? (MATLAB)

AI Thread Summary
The discussion focuses on building a matrix in MATLAB using "while" loops, specifically addressing an issue where the code only calculates the first row of the matrix. The user, Mike, shares his code and expresses confusion about why the program stops without completing the matrix. The solution proposed suggests that using "for" loops would be a better approach for this task, as they simplify the control structure. Additionally, a key fix for the "while" loop is to reset the inner loop variable, j, to 1 at the start of each iteration of the outer loop. This adjustment ensures that the inner loop executes correctly for each row of the matrix, allowing for the complete calculation of all elements in S.
mikeph
Messages
1,229
Reaction score
18
Building a matrix using "while" loops? (MATLAB)

Hello

Here is my code:

Code:
i = 1;
j = 1; 
S = zeros(11,11);

while i < 12
    while j < 12
        S(i,j) = Test1(a(i,j),b(i,j),c(i,j));
        j = j + 1;
    end
    i = i + 1;
end

a,b,c are all 11x11 matrices and Test1 is a function m-file which outputs a number. (I have tested it for all the values that a(i,j), b(i,j) and c(i,j) take).

My code is only calculating the first row of S, ie. S(2,1) = 0 still. I don't know why the program is ending without adding 1 onto i and repeating the loop, I can only imagine the "while" loop is the wrong way of going about this?

Thanks for any help,

Mike
 
Physics news on Phys.org


A better choice is a for loop for each of your loops.
Code:
for i=1:11
  for j = 1:11
     %% loop body
  end
end

You can do what you're doing with while loops, but they are in a sense more primitive control structures, so you have to do more of the work in your code. I think what might be happening is that after the inner loop has gone through a complete set of iterations, and i is now 2, you still have the last value of j (=12) in your inner loop. A fix for this problem might be like so:
Code:
while i < 12
    j = 1   %% added this line
    while j < 12
        S(i,j) = Test1(a(i,j),b(i,j),c(i,j));
        j = j + 1;
    end
    i = i + 1;
end
 
Back
Top