Access data in two dimensional struct array

59 visualizaciones (últimos 30 días)
J B
J B el 14 de Jul. de 2021
Respondida: Steven Lord el 14 de Jul. de 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?

Respuestas (1)

Steven Lord
Steven Lord el 14 de Jul. de 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

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by