Building a matrix using "while" loops? (MATLAB)


by mikeph
Tags: building, loops, matlab, matrix
mikeph
mikeph is online now
#1
Feb8-10, 05:43 AM
P: 1,199
Hello

Here is my 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
Phys.Org News Partner Science news on Phys.org
Better thermal-imaging lens from waste sulfur
Hackathon team's GoogolPlex gives Siri extra powers
Bright points in Sun's atmosphere mark patterns deep in its interior
Mark44
Mark44 is offline
#2
Feb8-10, 09:52 AM
Mentor
P: 20,962
A better choice is a for loop for each of your loops.
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:
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


Register to reply

Related Discussions
Help me design my "carputer" to work in the cold (advice on building a heater) Computing & Technology 10
building a "hybrid" and dynamic mathematical space Math & Science Software 0
New Loll "The Art of Building Spacetime" (Oriti's book) Beyond the Standard Model 0
building a "hybrid" and dynamic mathematical space Math & Science Software 0
"The Duel: Strings versus Loops" by Rudy Vaas Beyond the Standard Model 9