0

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!

1
  • You can use strmatch, and even have a cell array for all your strings, but you need to use any around the strmatch call. Commented Mar 20, 2012 at 13:18

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Indeed! I just realized I meant to use strmcp!
In general, though, even strcmp shouhld only be used when you want to check if a string is exactly the same as one other string. If you want to check if T is one of six allowable strings, use a regexp.
@Li-uang Yip: thanks for the regexp tip, it works beautifully!
1

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 !

2 Comments

Oh christ, how embarassing! I meant to use strcmp ...!
No need to call me Christ though I appreciate the sentiment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.