How can I access nested cell arrays in MATLAB?

Ben Fossen picture Ben Fossen · Jun 21, 2010 · Viewed 18k times · Source

I would like to make a nested cell array as follows:

tag = {'slot1'}
info = {' name' 'number' 'IDnum'}
x = {tag , info}

And I want to be able to call x(tag(1)) and have it display 'slot1'. Instead I am getting this error:

??? Error using ==> subsindex
Function 'subsindex' is not defined for values of class 'cell'.

If I call x(1) MATLAB displays {1x1 cell}. I want to be able to access the first cell in the list x so I can do a string comparison with another string.

I know I can write my own class to do this if MATLAB's built in class does not work but is there a simple trick to solve this problem?

Answer

gnovice picture gnovice · Jun 21, 2010

The return value of x(1) is actually a 1-by-1 cell array containing another 1-by-1 cell array which itself contains the string 'slot1'. To access the contents of cell arrays (and not just a subarray of cells) you have to use curly braces (i.e. "content indexing") instead of parentheses (i.e. "cell indexing").

For example, if you want to retrieve the string 'slot1' from x in order to do a string comparison, you could do it in one of two ways:

cstr = x{1};    %# Will return a 1-by-1 cell array containing 'slot1'
str = x{1}{1};  %# Will return the string 'slot1'

Then you can use the function STRCMP with either of the above:

isTheSame = strcmp(cstr,'slot1');  %# Returns true
isTheSame = strcmp(str,'slot1');   %# Also returns true

The above works because cell arrays of strings in MATLAB are handled somewhat interchangeably with strings and character arrays in many built-in functions.