Search code examples
matlabloopswhile-loopinfinite

MATLAB How did I make this loop, infinite + also how to shorten i = i + 1?


I thought this would be a simple iteration but apparently not, I keep seeing the numbers running up the screen and b = 425.0000 ... which should end my while loop but I have fluffed up royally!

temp = 85;
b = 85;
cntr = 0;

while b < 425
  temp = temp * 0.8
  b = b + temp
  cntr = cntr + 1
end;
cntr

Also in the above I have cntr = cntr + 1 but in other languages I could shorten this to cntr++ or cntr+=1 how can I do this in MATLAB?

Cheers!


Solution

  • Your condition should probably test whether the current value of b is close to the value of 425 up to a certain number of significant digits. you can do this as so:

    temp = 85; 
    b = 85; 
    cntr = 0; 
    
    while b < (425 - 0.0001)   #<--- however many significant digits you need.
      temp = temp * 0.8; 
      b = b + temp;
      cntr = cntr + 1;
    end
    
    cntr
    

    The problem is that your while loop is converging on 425, but never quite getting there.