Indexing structure fields?

Hi! I’m trying to get an index list of structure fields

>> aa.val                 ##  test struct
ans = L1
ans = L2
ans = N
>> aa(:).val               ##  how to tell a boy kitten from a girl kitten :-)
ans = L1
ans = L2
ans = N
v = L1                       ##  this isn't what I expected

I’ve even tried various

ans = type
>> aa.cell2mat(fieldnames(aa)(1))
error: structure has no member 'cell2mat'
>> aa(cell2mat(fieldnames(aa)(1)))
error: aa(121): out of bound 3 (dimensions are 1x3)

with no luck

How does one manipulate a structure without knowing what its fields are, like in a function?


aa(:).val returns a comma-separated-list. See Comma Separated Lists Generated from Structure Arrays (GNU Octave (version 6.4.0))

You could convert that to a cell array with {aa(:).val}.

1 Like

Thanks [mmuetzel]
But, at least on the command line,

v=aa(:).val      ## returns a 2-character string
v = L1                    


v={aa(:).val}     ## returns a cell array
v =
  [1,1] = L1
  [1,2] = L2
  [1,3] = N

Is the 1st case a bug?

strcmp("L2", {aa(1,:).type}) => [0 1 0]

Thanks again

Hi saintrain.

Isn’t a bug. When you’re calling aa(:).val, it returns the values as separate variables, if
you get the return as:

[a,b,c] = a(:).val

you can get all those elements but if you only write v = a(:).val, you will get only the first.

v = {aa(:).val} return all the elements agrupated into a matrix as mmuetzel says

1 Like

In many cases it is ok to think of a comma-separated-list (cs-list) as a substitute for the literal comma separated list.
E.g., s(1).f=1; s(2).f=2;, then s(:).f stands for 1, 2. In an assignment a=s(:).f;, you could substitute to a=1, 2;. That makes clear more intuitively why a=1 after that assignment.
On the other hand, b={s(:).f}; substitutes to b={1, 2};.


Thanks @89453728 and @mmuetzel!
I get it now.

1 Like