How to access data in a nested structures
Afficher commentaires plus anciens
Hi,
how do I access parts of the following structure:
a(1).b.c = 1;
a(2).b.c = 2;
I want a vector containing the c's.
This seems to work:
vec = cat(1,cat(1,a(:).b).c);
Is this the correct way?
Why does this not work:
[a(:).b].c
Thanks!
Réponse acceptée
Plus de réponses (2)
Walter Roberson
le 12 Juin 2020
a(1).b.c = 1;
a(2).b.c = 2;
arrayfun(@(S) S.b.c, a)
The above works only if the c is always a scalar.
a(1).b.c = [-1; 1];
a(2).b.c = [-2; 2];
cell2mat(arrayfun(@(S) S.b.c, a, 'UniformOutput', false))
This version works if the number of elements in c is the same each time, and the orientation of those elements is opposite the orientation of a. In the above example, the c are column vectors and a is a row vector and the result would have the c down columns.
a(1).b.c = [-1; 1];
a(2).b.c = [-2; 2];
cell2mat(arrayfun(@(S) S.b.c(:).', a(:), 'UniformOutput', false))
This version works if the number of elements in c is the same each time (but the shape does not need to be); the elements will become rows
temp = [a.b];
[temp.c]
This version works if the c are always scalar.
2 commentaires
The last syntax "This version works if the c are always scalar" or any compatible sizes, e.g.:
>> a(1).b.c = [1;3;5];
>> a(2).b.c = [2;4;6];
>> temp = [a.b];
>> [temp.c]
ans =
1.00 2.00
3.00 4.00
5.00 6.00
Markus
le 12 Juin 2020
Catégories
En savoir plus sur Functions dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!