How am I misunderstanding this if statement?
Show older comments
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
More Answers (1)
"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
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!