if statment. why do i receive following statment: Operands to the || and && operators must be convertible to logical scalar values.
1 次查看(过去 30 天)
显示 更早的评论
Hi all plz help me.I don't understand why following code is not working..
choice=input('enter something:','s');
if str2num(choice)==1 lower(choice) == 'load the data'
disp('loading the data')
end
when i run the code matlab says following:
Operands to the and && operators must be convertible to logical scalar values.
thx..
0 个评论
采纳的回答
Geoff Hayes
2014-6-21
编辑:Geoff Hayes
2014-6-21
The error is occurring when the user enters a choice that is non-numeric and the conversion from str2num is empty (i.e. []) which is NOT a logical scalar value operand to the (missing?) or () operator. (In the Command Window type str2num('hello') and observe the result.)
To get around this, you could convert the string to a number and check that it is not empty and equal to one, OR compare the string
choiceStr = input('enter something:','s');
choiceNum = str2num(choiceStr);
if (~isempty(choiceNum) && choiceNum==1) || lower(choiceStr) == 'load the data'
disp('loading the data');
end
Even the above is not quite correct. When comparing strings it is preferable to use the strcmp or strcmpi functions. Since you are not interested case (because of the lower) then just use strcmpi
choiceStr = input('enter something:','s');
choiceNum = str2num(choiceStr);
if (~isempty(choiceNum) && choiceNum==1) || strcmpi(choiceStr,'load the data')==1
disp('loading the data');
end
Try the above and see what happens!
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!