Search code examples
arraysmatlabcell

Cell array of strings - check elements in Matlab


In Matlab, if I have a cell array of strings, how can I check if for example 3rd row and 1st column is equal to some given string, for example 'ABC'?

For example, myArray(3,1) == 'ABC' gives me an error:

Undefined operator '==' for input arguments of type 'cell'.

Error in cw14 (line 19)
if myArray(3,1) == 'ABC'


Solution

  • That's because you need to use {curly braces} in order to access the content of the cell array.

    Using (regular brackets) indexes the actual cell, which in your case contains a string. Moreover, in order to check for the presence of strings I recommend using strcmp or maybe strfind.

    Therefore use this:

    strcmp(myArray{3,1},'ABC')
    

    Check here for infos about indexing into cell arrays.

    EDIT (following comments)

    Using logical == in order to find for strings into a cell array is not safe, because using this operator splits the strings and compares every letter forming it, as opposed to strcmp and the likes, that checks the whole string.

    Consider this code, where I put some strings into myArray:

    myArray = {'A' 'B' 'ABC' 'CBA' 'ABC'}.'
    
    myArray = 
    
        'A'
        'B'
        'ABC'
        'CBA'
        'ABC'
    

    If we apply == on this cell array of strings as follows:

    Check_31 = myArray{3,1} == 'ABC'
    
    Check_41 = myArray{4,1} == 'CB_'
    

    Matlab returns those 2 logical vectors:

    Check_31 =
    
         1     1     1
    
    
    Check_41 =
    
         1     1     0
    

    So as you see, the character "_" is not the last element of the string present in the cell {4,1}.

    Now if we use strcmp (on the whole cell array; we don't need to index specific cells to check whether some string is present):

    Check_ABC = strcmp(myArray,'ABC')
    

    We also get a logical vector, but this time not referring to the 3 letters forming the string inside the cell, but rather referring to the cell array itself and whether 'ABC' is present or not. The result is this:

    Check_ABC =
    
         0
         0
         1
         0
         1
    

    Which makes sense, since 'ABC' is indeed present in cells {3,1} and {5,1}.

    Hope that's clearer!