Cell Array of Strings - Control Elements in Matlab

In Matlab, if I have an array of row cells, how can I check if, for example, the 3rd row and 1st column is some given row, 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'

+5
source share
1 answer

This is because you need to use {curly brackets} to access the contents of an array of cells.

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

So use this:

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

Check here for information on indexing into cell arrays.

EDIT (following comments)

Using boolean == to search for strings in an array of cells is unsafe because using this operator breaks the strings and compares each letter that forms it, unlike strcmp and the like, which checks the entire string.

Consider this code where I put some lines in myArray :

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

If we apply == to this array of row cells as follows:

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

Matlab returns these two logical vectors:

 Check_31 = 1 1 1 Check_41 = 1 1 0 

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

Now, if we use strcmp (for the entire array of cells, we do not need to index specific cells to check if any row is present):

 Check_ABC = strcmp(myArray,'ABC') 

We also get a logical vector, but this time we don’t refer to the 3 letters that make up the string inside the cell, but referring only to the array of cells and whether "ABC" is present. The result is the following:

 Check_ABC = 0 0 1 0 1 

This makes sense, since "ABC" is actually present in cells {3,1} and {5,1}.

Hope that clearer!

+9
source

All Articles