Problem evaluating OR operator
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rodrigo Sánchez Suárez
el 8 de Nov. de 2022
Comentada: Steven Lord
el 8 de Nov. de 2022
I have what should be a simple problem, but after being stuck for a while, I dont know how to solve it.
Answer = '1';
if Answer == ('1') || ('2')
fprintf("inside if")
end
That works as it should, but when evaluating this case, it gives out an error which I don't understand why.
Answer = 'aa';
if Answer == ('1') || ('2')
fprintf("inside if")
else
fprintf("if didnt work")
end
I've checked out ANY and ALL functions, but dont seem to work for this. Im pretty sure this is a basic question but I'm stuck.
Thanks
0 comentarios
Respuesta aceptada
Jan
el 8 de Nov. de 2022
Editada: Jan
el 8 de Nov. de 2022
if Answer == ('1') || ('2')
Matlab evaluates this condition accourding to the precedence order of the operators from left to right:
1. Answer == ('1')
This replies true or false. In the next step this is used as 1st input of the || operator:
2. true || ('2') % or
false || ('2')
Both is not, what you want, but the (almost!) correct syntax is:
if Answer == ('1') || Answer == ('2')
Now the comparisons are processed at first - see: https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html
The next problem is that == is an elementwise operator:
'aa' == '1'
replies [false, false] , one logical for each element of the [1 x 2] char vector on the left. In the oiginal comparison this is used as 1st input of ||, which accepts scalar inputs only.
Use strcmp to compare char vectors instead:
if strcmp(Answer, '1') || strcmp(Answer, '2')
With strings (in double quotes), the == comparison is working:
Answer = "1";
if Answer == "1" || Answer == "2"
fprintf("inside if")
end
This is similar to another frequently ask question:
if a < b < c
This does not check, if b is between a and c. Correct:
is a < b && b < c
2 comentarios
Steven Lord
el 8 de Nov. de 2022
Other approaches that you could use instead of strcmp include matches, ismember, or (if you have a number of fixed sets of potential values that you want to match) switch and case.
s = ["1", "2", "3"]
matches(s, '2')
ismember(["2", "4"], s)
x = '2';
switch x
case {'1', '2'}
disp('Entered either 1 or 2')
case {'3'}
disp('Entered 3')
otherwise
disp('Entered something other than 1, 2, or 3')
end
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!