Search code examples
arraysmatlabassigncell-array

How to assign cell arrays to field in nested structure?


Suppose I have a cell array that I want to assign to a nested field.

myArray = {{ 1     2     3     4     5}; 
           { 7     8     9     10    11    12    13}}

I want the endresult to be something like:

myStruct(1).field = { 1     2     3     4     5}
myStruct(2).field = { 7     8     9     10    11    12    13}

Without actually having to access each individual field as I do in the above example. Also, I want to avoid using a for-loop.

Finally, how do we perform the inverse (again without accessing individual fields or using a for-loop): extract myArray from the myStruct structure?


Solution

  • There are two very specific MATLAB functions for this: cell2struct and struct2cell.

    For the first conversion, you just have to pay attention to use the correct axis by choosing the correct dim parameter. You have a 2 x 1 cell array here, so it's dim = 2.

    For the second conversion, you can just use struct2cell as is.

    Here's the complete code:

    myArray = {{ 1     2     3     4     5}; 
               { 7     8     9     10    11    12    13}}
    
    myStruct = cell2struct(myArray, 'field', 2);
    myStruct(1).field
    myStruct(2).field
    
    myArrayAgain = struct2cell(myStruct).'
    

    The output then looks like this (shortened):

      myArray =
      {
        [1,1] =
        {
          [1,1] =  1
          [1,2] =  2
          [...]
        }
    
        [2,1] =
        {
          [1,1] =  7
          [1,2] =  8
          [...]
        }
    
      }
    
      ans =
      {
        [1,1] =  1
        [1,2] =  2
        [...]
      }
    
      ans =
      {
        [1,1] =  7
        [1,2] =  8
        [...]
      }
    
      myArrayAgain =
      {
        [1,1] =
        {
          [1,1] =  1
          [1,2] =  2
          [...]
        }
    
        [2,1] =
        {
          [1,1] =  7
          [1,2] =  8
          [...]
        }
    
      }
    

    Hope that helps!