0
votes

I'd like to use a struct() to return various values in a Matlab function. One of those is a cell array. Here's an example:

xnames = cell( 3, 1 ) ;
for i = [1:3]
   xnames{i} = sprintf( 'V_%d', i ) ;
end

a = 1 ;
b = 2 ;
r = struct( 'a', a, 'b', b, 'x', xnames ) ;

However, if I attempt to access r.x, it appears that the original cell-identity is lost:

x = r.x ;
x{1}

This results in the error: 'Cell contents reference from a non-cell array object.' The string data appears to be there, as a display of r.x shows:

ans =

V_1


ans =

V_2


ans =

V_3

However, I don't know how to get at these fields after inserting the cell array into the struct?

EDIT: using the gui variable explorer for the above example, shows that r ends up with the results:

1   2   'V_1'
1   2   'V_2'
1   2   'V_3'

i.e. it got converted into an array of struct(), one for each of the values of xnames{i}:

>> r(1)

ans =

    a: 1
    b: 2
    x: 'V_1'

>> r(2)

ans =

    a: 1
    b: 2
    x: 'V_2'

>> r(3)

ans =

    a: 1
    b: 2
    x: 'V_3'

So, the problem isn't how to access this field x as a cell-array, but how to keep it a cell array on insertion into the struct() initializer?

2

2 Answers

5
votes

According to the documentation, the way the struct function handles cell arrays the way you call it means you would access V1, V2, V3 using

r(1).x
r(2).x
r(3).x

You can get the behaviour you want either by following David's suggestion or by using.

r.x = xnames;
4
votes

Enclose xnames in braces to keep it as a cell array:

r = struct( 'a', a, 'b', b, 'x', {xnames} ) ;