How am I misunderstanding this if statement?

The code:
x = [1 5 4 2];
if x > 3
m = x+1;
else
m = x - 1;
end
disp(m)
I expect that the resulting vector would be m = [0 6 5 1] since x(2) and x(3) > 3, however I'm getting m = [0 4 3 1]. Can anyone explain why this is?

 Accepted Answer

You need to use logical indexing. MATLAB does not understand what you meant properly. Try this:
x=[1 5 4 2];
x(x>3)=x(x>3)+1;
x(x<=3)=x(x<=3)-1

More Answers (1)

Stephen23
Stephen23 on 13 Feb 2018
Edited: Stephen23 on 13 Feb 2018
"Can anyone explain why this is?"
It is simple: if requires all of the conditions to be true. Clearly not all of x > 3 are true, so only the else branch will execute.
You could use logical indexing, but here is simple trick to get that result:
>> x = [1,5,4,2];
>> idx = x > 3;
>> m = x + idx -~idx
m =
0 6 5 1

Asked:

on 13 Feb 2018

Edited:

on 13 Feb 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!