How to use not equal to '~=' operator in if statement?
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (2)
Jan
am 21 Feb. 2017
Remember, that the negation of
(x=='A') || (x=='B')
is:
~((x == 'A') || (x == 'B')) ==>
~(x == 'A') && ~(x == 'B') ==>
(x ~= 'A') && (x ~= 'B')
3 Kommentare
Zhuoying Lin
am 28 Nov. 2017
Bearbeitet: Walter Roberson
am 28 Nov. 2017
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
am 28 Nov. 2017
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
By the way, you can get the error about operands must be convertible, if the value in x is not a scalar. You should not use ~= to compare character vectors to characters: doing so will compare each element of the character vector in turn
x = 'ab';
x ~= 'a'
Notice the array of output values.
You should use ismember to compare -- or you should convert to string() objects
ismember(x, {'a', 'p', 'T'})
ismember(x, {'aa', 'ab', 'ac'})
string(x) ~= 'a'
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.
Kategorien
Mehr zu Startup and Shutdown finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!