Help: if condition with evaluating multiple statements?

1 回表示 (過去 30 日間)
Khanh
Khanh 2014 年 10 月 28 日
コメント済み: Khanh 2014 年 10 月 29 日
Hi everybody,
My sample if condition have 3 expression. As the following code, how can I evaluate statement 2 and statement 3 when the expressions are true?
a=1
b=1
c=3
if c==2
disp('C=2')
elseif a~=c
disp('a~=c') % Statement 2
elseif a~=c && b~=c
disp('a&b~=c') % Statement 3
end
When I run the code, it just showed 'a~=c', eventhough the expression 'a~=c && b~=c' is true.
Thanks.

採用された回答

Mischa Kim
Mischa Kim 2014 年 10 月 28 日
編集済み: Mischa Kim 2014 年 10 月 28 日
Khanh, only one of the if ( elseif ) statements is executed. In your case it is the second one, because it is the first condition that evaluates true.
Use instead:
if c==2
disp('C=2')
elseif a~=c
if b~=c
disp('a&b~=c') % Statement 3
else
disp('a~=c') % Statement 2
end
end
  1 件のコメント
Khanh
Khanh 2014 年 10 月 29 日
Thank you so much. Your answer makes me more understood about using if condition. Actually, I want to show both 'a&b~=c' and 'a~=c' and I found that I have to use each if-end with each expression. It will be as:
if c==2
disp('C=2')
end
if a~=c && b~=c
b~=c
disp('a&b~=c') % Statement 3
end
if a~=c
disp('a~=c') % Statement 2
end
And the command window will show both statement 2 and 3.
Thanks again man.

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by