Search code examples
matlablistcontain

Check existence of element in list of elements


In Python one can do something like this

the_weather_is = 'sunshiny'

bad_mood = {'dreary', 'drizzly', 'flawy', 'blustery', 'thundery'}

if the_weather_is in bad_mood:
    print 'Stay at home...'
else:
    print 'All fine...'

How would the MATLAB equivalent look like, i. e. have a list of strings (options) and check if string is in list?

Actually I don't even know, what one can use as list in MATLAB. CellArrays?


Solution

  • bad_mood is not a list, it's a cell array.

    You could use ismember function to check if the_weather_is is in a bad_mood cell array:

    ismember(the_weather_is, bad_mood)
    

    Alternative solution (from Benoit_11's answer) is to use strcmp function, combined with any function:

    any(strcmp(the_weather_is, bad_mood))
    

    strcmp compares the_weather_is with each string of bad_mood cell array and returns a logical array. any checks that returned logical array contain at least one true value.