matlaboctavecell-arraymatlab-struct

Convert struct array to cell of structs and vice versa


I often have to work with struct arrays and cells containing scalar structs with identical fieldnames which I call an "unpacked struct array" and I wonder if there aren't already functions in Matlab and/or GNU Octave which helps converting between those two representations.

A struct array:

foo(1).a = 3;
foo(1).b = pi;
foo(2).a = 5;
foo(2).b = 2.718;

Apparently num2cell works in one way in GNU Octave (although it isn't mentioned in the docs):

ret = num2cell (foo)
ret =
{
  [1,1] =

    scalar structure containing the fields:

      a =  3
      b =  3.1416

  [1,2] =

    scalar structure containing the fields:

      a =  5
      b =  2.7180

}

But I'm looking for the reverse part, converting ret back to foo.


Solution

  • This seems to do what you want:

    foo2 = [ret{:}]; % or equivalently foo2 = horzcat(ret{:});
    

    That is, just concatenate the cell array's contents horizontally.

    Check:

    >> foo(1).a = 3;
    foo(1).b = pi;
    foo(2).a = 5;
    foo(2).b = 2.718;
    >> ret = num2cell (foo);
    >> foo2 = [ret{:}];
    >> isequal(foo, foo2)
    ans =
      logical
       1