Louis Thibault
Louis Thibault

Reputation: 21470

Why can I not chain logical comparisons in an if statement?

I'm trying to execute a block of code if one of several conditions is met. Again, for clarity, if any of the conditions are true, I'd like for the code to execute (chain of logical ORs).

When I type this code into Matlab:

if strmatch(T,'Sd') || strmatch(T,'SuperDev') || ...
        strmatch(T,'lrnTrialVD') || strmatch(T,'lrnTrialVIS') || ...
        strmatch(T,'lrnTrialTARGET') || strmatch(T,'lrnTrialAUD')

I get this error:

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

Can someone please tell me where I've gone wrong?

/blz

EDIT: I used the wrong function. strcmp is what I meant to use!

Upvotes: 0

Views: 835

Answers (2)

Li-aung Yip
Li-aung Yip

Reputation: 12486

I believe this is because the return value of strmatch() is an array, not a scalar, and || might not be defined on array arguments. I don't have MATLAB in front of me (only Octave), but does [1, 2, 3] || [4, 5, 6, 7] work for you?

Additonally, it would be better to match a regular expression like (Sd|SuperDev|lrnTrial(VD|VIS|TARGET|AUD)) which is a bit more compact, more readable, and only needs to inspect the string 'T' once (not six times.)

This would look like:

octave-3.2.4.exe:10> T1 = "Sd"
T1 = Sd
octave-3.2.4.exe:11> T2 = "Lollipop"
T2 = Lollipop
octave-3.2.4.exe:12> regexp(T1,"(Sd|SuperDev|lrnTrial(VD|VIS|TARGET|AUD))" )
ans =  1
octave-3.2.4.exe:13> regexp(T2,"(Sd|SuperDev|lrnTrial(VD|VIS|TARGET|AUD))" )
ans = [](1x0)

Upvotes: 3

High Performance Mark
High Performance Mark

Reputation: 78364

strmatch doesn't necessarily return something which can be converted to a logical scalar value. It might, for example, return a vector of match locations which does not convert without further effort on your part. It's all there in the error message and the product documentation, it really is !

Upvotes: 1

Related Questions