Access data in two dimensional struct array

조회 수: 14 (최근 30일)
J B
J B 2021년 7월 14일
답변: Steven Lord 2021년 7월 14일
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?

답변 (1개)

Steven Lord
Steven Lord 2021년 7월 14일
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

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by