MATLAB Answers

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

조회 수: 1,825(최근 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
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.

Community Treasure Hunt

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

Start Hunting!

Translated by