second expression and second statement doesn't excuted in else if ?
1 view (last 30 days)
Show older comments
why the second condition and second statments don't take into account (doeasn't excuted ) ? when I excuted the code only the first condition and its statment excuted as well as to the last statement
if condition 1
do some calculation 1
elseif condition 2
do some calculation 2
else
do some calculation 3
end
Accepted Answer
Steven Lord
on 24 Aug 2022
In an if / elseif / else statement like this:
%{
if condition 1
do some calculation 1
elseif condition 2
do some calculation 2
else
do some calculation 3
end
%}
one and only one of calculations 1, 2, and 3 will be executed each time this section of code runs. I've wrapped it in a block comment so I can run code later in this answer without having the code above error because MATLAB can't run "if condition 1".
If condition 1 is true, MATLAB will execute calculation 1 and then will skip to immediately after the end. MATLAB doesn't even check condition 2 in this case. So condition 2 could error if it were executed and MATLAB wouldn't care.
if true
disp('Hello')
elseif ones(2) > ones(3) % mismatched sizes, this check would error
disp('Goodbye')
end
If condition 1 is false and condition 2 is true, MATLAB will execute calculation 2 and then will skip to immediately after the end.
if false
disp('Hello')
elseif true
disp('Goodbye')
else
disp('What?')
end
If condition 1 is false and condition 2 is false, MATLAB will execute calculation 3 and then will skip to immediately after the end.
if false
disp('Hello')
elseif false
disp('Goodbye')
else
disp('What?')
end
Another potential problem you could be experiencing is that your conditions involved vectors and you expected the body of the if statement to operate only on those elements of the vector that satisfied the condition, then for MATLAB to check the rest of the elements against the condition of the elseif statement, etc.
x = 1:5;
if x > 3 % [false false false true true]
disp('Hello')
elseif x > 1 % [false true true true true]
disp('Goodbye')
else
disp('What?')
end
that is not how MATLAB behaves. If the condition of an if or elseif statement is neither a scalar nor an empty, all the elements of the condition must be true for the condition to be satisfied. If there's even one false (as in the x > 1 case in the example above) the body of that if or elseif is not executed. For this case you'd want to use logical indexing. And you'd probably want to be careful about the order in which you executed those steps.
y = zeros(size(x));
y(x > 3) = x(x > 3).^2
y(x > 1) = x(x > 1).^3
z = zeros(size(x));
z(x > 1) = x(x > 1).^3
z(x > 3) = x(x > 3).^2
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!