Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why "if InputText == '0' || isempty(InputText)" in MATLAB is giving error?

if InputText == '0' || isempty(InputText)

in MATLAB is giving error:

Operands to the || and && operators must be convertible to logical scalar values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m looking for an explanation for it. Isn’t InputText == '0' returning a logical value nor the other? Definitely the second is, so what’s the problem with InputText == '0'?

I have a MATLAB script and I want to ask user finish a procedure by either entering a ‘0’ or just pressing space in it; here is the code:

if InputText == '0' || isempty(InputText)
    break
end

and here is the error I get consequently:

Operands to the || and && operators must be convertible to logical scalar values.

Error in test (line 11)
if InputText == ‘0’ || isempty(InputText)

>Solution :

If InputText = '012' then you can see what your first check outputs:

InputText == '0'
>> 
 ans = [true, false, false]

The single quotes indicate a character array, and it is treated similarly to numeric arrays for comparisons, so the output of the == '0' operation is a comparison of each element with '0'. This means the output is nonscalar, so you can’t use it with && or ||.

If you want to check "is the whole character array InputText equivalent to '0'?" then you should use strcmp

So your condition would be

if strcmp(InputText, '0') || isempty(InputText)
    break
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading