about logical operator in if!

This is my code
y = input('choose','s');
if y == 'a1' | y == '1a'
disp('win')
else
disp('lost')
end
I would like to ask that when I use this, while I am run this program, I type only a or only 1 it also display win, like i type 1a or a1 . explain to me, or me have other ways to write the code, I do not need to add elseif more.
Thanks!

Respuestas (1)

Matt J
Matt J el 25 de Mayo de 2014
Editada: Matt J el 25 de Mayo de 2014

2 votos

Use strcmp()
if strcmp(y,'a1') || strcmp(y,'1a')
disp('win')
else
disp('lost')
end
As for understanding what's happening currently, observe the result of each of your sub-expressions, and the vectors of logical data they produce, when y='1',
>> y='1';
>> y == 'a1'
ans =
0 1
>> y == '1a'
ans =
1 0
>> y == 'a1' | y == '1a'
ans =
1 1
Since (y == 'a1' | y == '1a') produces a vector of trues, the whole if statement evaluates to true. As mentioned in "doc if",
" An evaluated expression is true when the result is nonemptyand contains all nonzero elements (logical or real numeric). Otherwise,the expression is false. "

5 comentarios

Matt J
Matt J el 25 de Mayo de 2014
You could also use ismember
if ismember(y,{'a1','1a'})
disp('win')
else
disp('lost')
end
Matt J
Matt J el 26 de Mayo de 2014
chan Commented:
Thanks for the good, answer, so mean we cannot use the simple condition, right? y == 'a1' | y == 'a1'
Jos (10584)
Jos (10584) el 26 de Mayo de 2014
to see if two things are equal use isequal, rather than ==
isequal(y,'a1')
For character arrays (strings) A and B, you can use strcmp(A,B)
For numerical arrays A and B (of the same length!), you may use all(A==B)
Matt J
Matt J el 26 de Mayo de 2014
Editada: Matt J el 26 de Mayo de 2014
to see if two things are equal use isequal, ... isequal(y,'a1')
Be careful when using isequal to compare strings. It doesn't check that both arguments are class char, e.g.,
>> isequal(':',58)
ans =
1
whereas,
>> strcmp(':',58)
ans =
0
Matt J
Matt J el 26 de Mayo de 2014
so mean we cannot use the simple condition, right? y == 'a1' | y == 'a1'
You can use these kinds of comparisons when they are appropriate to what you are doing. For example, suppose I want to remove all the spaces in a string,
>> y='This is a short string'; y(y==' ')=''
y =
Thisisashortstring

La pregunta está cerrada.

Etiquetas

Preguntada:

el 25 de Mayo de 2014

Cerrada:

el 20 de Ag. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by