How to use not equal to '~=' operator in if statement?

471 ビュー (過去 30 日間)
Sohail Ahmed
Sohail Ahmed 2017 年 2 月 21 日
コメント済み: Walter Roberson 2017 年 11 月 28 日
My code works fine with '==' but not with '~='.I expect it not to display 'error' if user enters A or B
x=input('input x','s')
if(x~='A')||(x~='B')
disp('error');
end

採用された回答

John D'Errico
John D'Errico 2017 年 2 月 21 日
編集済み: John D'Errico 2017 年 2 月 21 日
A problem of elementary logic?
You want an error to return only if A is not in the set {'A','B'}. So a call to ismember might be a good alternative.
Regardless, given the approach you have followed, if x is equal to 'A', then the second half of the clause will be true, even though the first part of the clause is false. And the logical statement
false || true
is TRUE.
You are asking for a result that is only true when BOTH parts of the clause are true. Use a logical and, NOT a logical or.
if(x~='A') && (x~='B')

その他の回答 (2 件)

Jan
Jan 2017 年 2 月 21 日
Remember, that the negation of
(x=='A') || (x=='B')
is:
~((x == 'A') || (x == 'B')) ==>
~(x == 'A') && ~(x == 'B') ==>
(x ~= 'A') && (x ~= 'B')
  2 件のコメント
Zhuoying Lin
Zhuoying Lin 2017 年 11 月 28 日
編集済み: Walter Roberson 2017 年 11 月 28 日
Hi I have a similar question:
when I type:
if (x ~= 'a') && (x ~= 'p') && (x ~= 'T')
fprintf('ERROR:You entered incorrect choice.')
end
but it also shows that:
Operands to the || and && operators must be convertible to
logical scalar values.
Error in term (line 4)
if (x ~= 'a') && (x ~= 'p') && (x ~= 'T')
Walter Roberson
Walter Roberson 2017 年 11 月 28 日
if any((x ~= 'a') & (x ~= 'p') & (x ~= 'T'))
fprintf('ERROR:You entered incorrect choice.')
end
or
if ~all( ismember(x, {'a', 'p', 'T'}) )
fprintf('ERROR:You entered incorrect choice.')
end

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


Torsten
Torsten 2017 年 2 月 21 日
編集済み: Torsten 2017 年 2 月 21 日
If user enters A, then x~=B is true, so (x~='A')||(x~='B') is true, thus "error" is displayed.
Same for B.
Best wishes
Torsten.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by