MATLAB: This should be easy I have a while loop that is infinite

infinite loopsMATLABwhile loop

When I run this it is inifinite and well that's not what i am looking for… i thought that by limiting the x value to 99 which is in the vector i could get it to stop but that's not the case. any ideas i know that it is going to be something simple…
clc, clear all, close all;
x = 1;
while x <= 99
x = 1:2:100

Best Answer

  • In MATLAB, conditionals evaluate to true if ALL values of the conditional are non-zero or true. You are repeatedly creating a vector x inside the loop which has all of its values equal to or less than 99, so the conditional will evaluate to true every time. This is why you are getting an infinite loop.
    Here is an example, using an IF statement. It evaluates the same way the WHILE loop does:
    v = [1 2 -9]; % Notice ALL values are non-zero
    if v, disp('IN IF 1'),end
    v = [1 0 -9]; % Not all values are non-zero.
    if v, disp('IN IF 2'),end
    When you do a comparison (>,<,==, etc), you get a logical result. If you do a comparison on an array, you get a logical vector the same size as the array. This will go through a conditional expression the same as v did above: any false (0) values and the expression will not pass the statement.
    v>-20 % This will pass [1 1 1]
    v<0 % Will not pass, [0 0 1]
    What are you trying to achieve with your loop?