Search code examples
matlabcell-array

Convert Matlab struct array to cell array


Can a Matlab struct array be converted to a cell array without iterating through the array?

I want each struct in the struct array to become one cell in the cell array. The command struct2cell doesn't seem to do it as it breaks out each field in the struct into a separate cell.

This has been posted to:


Solution

  • Try num2cell:

    myStructCell = num2cell(myStruct);
    

    For example:

    >> myStruct(1).name = 'John';
    >> myStruct(2).name = 'Paul';
    >> myStruct
    
    myStruct = 
    
    1x2 struct array with fields:
    
        name
    
    >> myStructCell = num2cell(myStruct)
    
    myStructCell = 
    
        [1x1 struct]    [1x1 struct]
    
    >> myStructCell{1}
    
    ans = 
    
        name: 'John'
    
    >> myStructCell{2}
    
    ans = 
    
        name: 'Paul'
    
    >> myStructCell{2}.name
    
    ans =
    
    Paul