Gautam Krishna
Gautam Krishna

Reputation: 139

Matlab: Updating max count in a loop doesn't work

I have executed this simple loop script in MATLAB

clc;clear; close all;
m = 100;
for i = 1:m
    if(i == 2)
        m = 1000;
    end
end 

and found, that 'i' loops only till '100' BUT NOT '1000'. Why..??

Upvotes: 3

Views: 74

Answers (2)

Joseph Sayegh
Joseph Sayegh

Reputation: 25

I'm not an expert but the for loop replace the m var with 100 in the first run and then it performs the loop as from 1 to 100 (not 1 to m) and it doesnt check every run what is m it knows that m is 100 and it runs until it reaches 100 if for example your script is like this:

<code>
m=100;
for i=1:m (m is 100)
 if(i==2)
  m=1000;
  for i=1:m (m is 1000)
    a=xyz;
   end
  end
end
</code>

Upvotes: -2

Jonas
Jonas

Reputation: 74940

The statement for i=1:m assigns the array 1:m to the list of values the operator will take on during the loop. This happens when the loop starts executing (note: you can use any array, and it'll be worked through column by column; for letter='abcde';fprintf('%s\n',letter);end works fine).

If you want to adjust how often your loop will be iterated through, I recommend using a while loop:

ct = 1;
maxIterations = 100;
success = false;
while ~success
   fprintf('iteration %i/%i\n',ct,maxIterations);
   ct = ct + 1;
   if ct == 2
      maxIterations == 1000;
   end

   if ct > maxIterations
       success = true;
   end
end

Upvotes: 4

Related Questions