MATLAB: Accessing all the values of a specific structure field in a matrix of structure to a cell array.

cell arraysstructstructures

I have an array of structure: RList with the fields a,b,c,d. This array has a size, say, 1*50.
RList(1).a = [1 2 3;5 6 7]
RList(1).b = [-5 6 9;15 2 7]
RList(1).c = [6 6 2]
RList(1).d = [1 5 1;9 3 11]
RList(2).a = [11 5 67;2 8 4; 4 24 6]
RList(2).b = [-5 26 9]
RList(2).c = [1 -7 67;4 67 8]
RList(2).d = [8 1 1;6 1 3]
.
.
.
RList(50).a = [11 67 3;6 9 -4]
RList(50).b = [-35 6 21;1 8 99]
RList(50).c = [0 56 -6]
RList(50).d = [1 3 6;29 -3 16; 1 7 12]
Now I want to put all the values in field 'a' to a 2D cell array, something like
for x = 1:N
RList(1,:) = func(x);
All_a(x,:) = RList(1,:).a
end
So in the end, I should have a 2D cell array with only values of 'a'.
All_a{1,1} = [1 2 3;5 6 7]
All_a{1,2} = [11 5 67;2 8 4; 4 24 6]
.
.
All_a{1,50} = [11 67 3;6 9 -4]
All_a{2,1} = ....
All_a{2,2} = ....
.
.
All_a{2,50} = ....
.
.
.
Can I extract all the values of field 'a' without doing an element to element copy in a loop?

Best Answer

for x = 1:N
%I'm not sure why you used RList(1, :) which will result in an error
%if numel(Rlist(1, :)) ~= numel(func(x))
%Using just plain assignment
RList = func(x);
All_a(x, :) = {RList.a}; %assign all a fields to cell array
end
The above uses matlab's concept of comma-separated lists. RList.a (when RList is a structure array) returns a comma separated list of all the a values. This is then wrapped into a cell array with {}.
Alternatively, you could build a 2d structure array in the loop and convert it all at once to a cell array afterward, using struct2cell:
RList = []; %make sure it is empty to avoid errors in the assignment
for x = 1:N
RList(x, :) = func(x);
end
All_fields = struct2cell(RList); %returns a numfields * N * 50 cell array
All_fields = squeeze(All_fields(strcmp('a', fieldnames(RList)), :, :)); %filter 'a' field
Related Question