Problem evaluating OR operator

4 ビュー (過去 30 日間)
Rodrigo Sánchez Suárez
Rodrigo Sánchez Suárez 2022 年 11 月 8 日
コメント済み: Steven Lord 2022 年 11 月 8 日
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
inside if
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
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
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

採用された回答

Jan
Jan 2022 年 11 月 8 日
編集済み: Jan 2022 年 11 月 8 日
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 件のコメント
Rodrigo Sánchez Suárez
Rodrigo Sánchez Suárez 2022 年 11 月 8 日
Beautiful, thanks!
Steven Lord
Steven Lord 2022 年 11 月 8 日
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"]
s = 1×3 string array
"1" "2" "3"
matches(s, '2')
ans = 1×3 logical array
0 1 0
ismember(["2", "4"], s)
ans = 1×2 logical array
1 0
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
Entered either 1 or 2

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by