3

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.

Andy
  • 7,931
  • 4
  • 25
  • 45

1 Answers1

5

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Omg, I now remember that I've done this before a year ago while working with image regionprops centroids.... I completly forgot that it's possible to concatenate scalar structs if the fields are identical. – Andy Nov 17 '17 at 14:14
  • 1
    _I now remember that I've done this before a year ago_: happens to me a lot :-) – Luis Mendo Nov 17 '17 at 14:15