if statment. why do i receive following statment: Operands to the || and && operators must be convertible to logical scalar values.
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
Geoff Hayes
on 21 Jun 2014
Edited: Geoff Hayes
on 21 Jun 2014
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 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!