Building a matrix using while loops? (MATLAB)

Click For Summary
SUMMARY

The discussion focuses on building a matrix using "while" loops in MATLAB, specifically addressing an issue with the inner loop not resetting the variable 'j'. The user, Mike, encounters a problem where only the first row of the matrix 'S' is being calculated due to 'j' retaining its last value after the inner loop completes. A solution is provided, which involves resetting 'j' to 1 at the start of each iteration of the outer loop. Additionally, the suggestion to use "for" loops is presented as a more efficient alternative for this task.

PREREQUISITES
  • Understanding of MATLAB programming language
  • Familiarity with matrix operations in MATLAB
  • Knowledge of control structures, specifically loops
  • Experience with function m-files in MATLAB
NEXT STEPS
  • Learn about MATLAB "for" loops for matrix manipulation
  • Explore MATLAB function m-files and their usage
  • Investigate debugging techniques in MATLAB to identify loop issues
  • Study best practices for optimizing MATLAB code performance
USEFUL FOR

MATLAB programmers, data analysts, and anyone looking to improve their skills in matrix manipulation and control structures within MATLAB.

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
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
3
Views
2K
  • · Replies 41 ·
2
Replies
41
Views
10K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
5
Views
2K
  • · Replies 4 ·
Replies
4
Views
7K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K