14

I wanted to wrap up a few variables inside a single struct, for easier input and output from functions as they are sent around quite a bit. The problem is that one of the variables is a cell array - specifically containing strings. Evidently once one of the variables given to

struct(var1,var2,...) 

is a cell array, then it makes the struct a cell array of structs, instead of having the cell array an inner variable of the struct - which is not my desired outcome and would require uglyfing lots of code.

Is there any solution/workaround to this issue?

dan12345
  • 1,594
  • 4
  • 20
  • 30
  • 5
    This was addressed in a prior duplicate: [MATLAB "bug" (or really weird behavior) with structs and empty cell arrays](http://stackoverflow.com/questions/939544/matlab-bug-or-really-weird-behavior-with-structs-and-empty-cell-arrays). The solution is that you have to wrap a cell array value for a field in an additonal cell array when passing it to the STRUCT function. – gnovice May 08 '11 at 15:17

1 Answers1

30

You can set the field directly:

 X = struct('a', 'one', 'b', 'honk');
 X.c = {'x', 'y'};

Or, if you want to do everything inside struct() you can put the cell array into a cell array:

X = struct('a', 'one', 'b', 'honk', 'c', {{'foo', 'bar'}});
X = 
    a: 'one'
    b: 'honk'
    c: {'foo'  'bar'}
Alex
  • 5,863
  • 2
  • 29
  • 46