Search code examples
matlabif-statementconditional-statementslogical-operatorslogical-or

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.

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