Error using logical operators on a string input
23 ビュー (過去 30 日間)
古いコメントを表示
Hi! I want accept if the user input a string, for example: wefef, so i put my input with ('s').
Then i create i while loop to check if that input it´s different from 1 our 2, if its empty and if it´s a string, in this case I want to appear a error mesage.
My code isn´t working, it´s giving me error: 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.
Can you help me? Thanks a lot!
elseif b==2
a1= sprintf('If you want to advance in the program, press 1. If you want to go back to the previous menu, press 2: ');
b1=(input(a1,'s'));
while (b1 ~= 1) && (b1 ~= 2) && (isempty(b1) || isstring(b1))
clc
errordlg ({'Incorrect option entry.','Please press Ok and enter the desired value in the Command Window.'})
a1= sprintf('If you want to advance in the program, press 1. If you want to go back to the previous menu, press 2: ');
b1=(input(a1,'s'));
end
2 件のコメント
回答 (2 件)
Walter Roberson
2023 年 1 月 15 日
input with the 's' option returns a character vector, possibly with multiple characters, possibly empty. isstring() for it will always be false but ischar() would be true.
Remember that character vectors are vectors. If the user enters 21 then that would be ['2' '1'] and then comparing to 1 would be ['2'==1, '1'==1] which would be a vector result [false false] but && requires that the sides return scalar. Notice that '1'==1 is false because '1' has character code 49 which is not 1.
And remember that []==1 would return an empty logical vector but && needs a scalar
Use strcmp to compare character vectors, and compare them against characters not against numeric values (unless you know what you are doing)
Sulaymon Eshkabilov
2023 年 1 月 15 日
編集済み: Sulaymon Eshkabilov
2023 年 1 月 15 日
Here is the corrected part of your code.
Note that you'd need to get a single value logical in order to compare the two different logicals, and thus, use any()
...
a1= sprintf('If you want to advance in the program, press 1. If you want to go back to the previous menu, press 2: ');
b1=(input(a1,'s'));
while any(b1 ~= 1) && any(b1 ~= 2) && isempty(b1) || isstring(b1)
clc
errordlg ({'Incorrect option entry.','Please press Ok and enter the desired value in the Command Window.'})
a1= sprintf('If you want to advance in the program, press 1. If you want to go back to the previous menu, press 2: ');
b1=(input(a1,'s'));
end
3 件のコメント
参考
カテゴリ
Help Center および File Exchange で Whos についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!