Access data in two dimensional struct array

14 views (last 30 days)
J B
J B on 14 Jul 2021
Answered: Steven Lord on 14 Jul 2021
I have a struct array with two dimensions:
temp = struct('a',5,'b',7);
bla = repmat(temp,4,8);
I would now like to get the data from one field as a matrix:
data = [bla.a];
However, I now get a vector with all the entries in one dimension. I would like to keep the matrix dimensions, e.g. something like that:
data = zeros(size(bla));
for i=1:size(data,1)
for j=1:size(data,2)
data(i,j) = bla(i,j).a;
end
end
Is there a more elegant way to do this?

Answers (1)

Steven Lord
Steven Lord on 14 Jul 2021
There's no guarantee that the field in the elements of a struct array have the same type or size, so making an array may not make sense. The best you could do in general would be to make a cell array and reshape it. That same technique would work with a regular array if all the fields have scalars that can be concatenated, too.
s1 = repmat(struct('x', 1), [3 3]);
for k = 1:numel(s1)
s1(k).x = k+zeros(k);
end
A = {s1.x}
A = 1×9 cell array
{[1]} {2×2 double} {3×3 double} {4×4 double} {5×5 double} {6×6 double} {7×7 double} {8×8 double} {9×9 double}
B = reshape(A, size(s1))
B = 3×3 cell array
{[ 1]} {4×4 double} {7×7 double} {2×2 double} {5×5 double} {8×8 double} {3×3 double} {6×6 double} {9×9 double}
check = isequal(B{2, 3}, s1(2, 3).x)
check = logical
1

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!