views:

59

answers:

2

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?

+8  A: 

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.

gnovice
+3  A: 

Instead of using a cell array, you could use a structure:

x(1) = struct('tag','slot1','info',{{'something'}}); %# using '1' in case there are many

Then, you get the first tag as

x(1).tag

Alternatively, you could use tag names as fieldnames. If tag names and information are cell arrays, you can pass the cell arrays instead of 'slot1' and 'information here', and you have the structure created in one go.

x = struct('slot1','information here')
tagName = 'slot1';
%# access the information via tag names
x.(tagName)
Jonas

related questions