Query a variable from a MATLAB structure array
I have an array of structures in MATLAB, all of which have the same structure (same fields). I would like to quickly compile an array containing all the values โโof a specific field from a struct array. Is there a way to do this without using loops?
Thank you in advance
Suppose your array has a name a
and you have a field b
. Access a.b
gives you a list of field values b
for each item in the a
. If you want to turn this into a list, just wrap the list in []
. I.e:
>> a = [struct('a', 1, 'b', 10, 'c', 100), struct('a', 2, 'b', 20, 'c', 200)];
>> a
a =
1x2 struct array with fields:
a
b
c
>> a.b
ans =
10
ans =
20
>> [a.b]
ans =
10 20
>> [a.c]
ans =
100 200
If you have a matrix of structures, you can use the above method to get a vector, which then converts it to a matrix using:
>> reshape([a.b], size(a))
ans =
10 111
20 222