Home > Software design >  If statements in for loop don't work correctly - MATLAB
If statements in for loop don't work correctly - MATLAB

Time:05-08

for h=0:39
if h<10
    disp('primi 10')
elseif 10<=h<20
    disp('primi 20')        
elseif 20<=h<30
    disp('primi 30')
elseif 30<=h<40
    disp('primi 40')
end
end

The simple code above is the one that I've try to run in MATLAB, but as output I get something strange like:

primi 10
primi 10
primi 10
primi 10
primi 10
%first 10 senteces are corrected
...
primi 10
primi 20
primi 20
primi 20
.....
%until the end of the loop

So it seems that matlab doesn't exit from the

elseif 10<=h<20 disp('primi 20')

statement. In fact the first 20 iterations are corrected, while the others no. I really don't know how to correct it. Any suggestions?

CodePudding user response:

You should combine the “singular” conditions with logical operators, such as “elseif 10<=h && h<20”. In your case, the compiler saw 10<=h first and resolved it as True and then proceeded to compare True<20, which is True as well, so everything was printed as 20.

  • Related