Search code examples
arraysmatlabcell-array

Use contents of a cell to name cell array?


I have a cell array of cell arrays in Matlab, and I want to simplify things by naming each cell array based on the contents of one of it's cells. Here is an example:

myCell1 = {'';'name1'; 'stuff';'two';'three'};
myCell2={'';'name2';'more stuff';'4';'things'};
Cell={myCell1, myCell2}

If I have Cell in the example above, I want to create two unnested cell arrays named based on the second row in each of them. In this example, the result would be as follows:

name1 = 

''
'name1'
'stuff'
'two'
'three'

name2 = 

''
'name2'
'more stuff'
'4'
'things'

How can I do this? I tried indexing as follows, but it doesn't work (I don't how to make MATLAB recognize that I want the string in the cell array to be a name).

Cell{1,1}{2}=Cell{1,1};

Solution

  • You can use eval to do this for you. Basically, you create a command you would like executed in MATLAB as a string, then use eval to execute this command for you. As such, you can do something like this:

    for idx = 1 : numel(Cell)
        cel = Cell{idx}; %// Extract i'th cell
        name = cel{2}; %// Get the name
        %// Create a cell array of this name in your workspace
        st = [name ' = cel;'];
        eval(st);
    end
    

    What the above code is doing is that it accesses each nested cell in your overall cell array, extracts the name of the cell, uses eval to take that name of the cell, make that a variable and assign this to the nested cell that you extracted.


    By executing this code, I get:

    name1 = 
    
    ''
    'name1'
    'stuff'
    'two'
    'three'
    
    
    name2 = 
    
    ''
    'name2'
    'more stuff'
    '4'
    'things'