array of structs how to preallocate and assign

81 vues (au cours des 30 derniers jours)
Leos Pohl
Leos Pohl le 6 Sep 2021
Réponse apportée : Jan le 6 Sep 2021
I have a struct;
s.a = 1;
s.b=[1 2 3];
and i want a struct array such that:
sa(1).a = 1;
sa(1).b=s.b=[1 2 3];
sa(2).a=3;
sa(2).b=[0 0 0];
and so on. Assignment to sa is done in a loop. How do i preallocate sa? I tried
sa = struct([]);
sa = zeros(1,n);
but none of the above works. If I do not preallocate, matlab warns about speed of the code.
Another question is, how do I assign s to sa(i)? That is how to make the following work:
sa(1) = s;

Réponses (1)

Jan
Jan le 6 Sep 2021
An easy way is to create the struct array backwards:
sa = struct([]);
for k = 3:-1:1
sa(k).a = k;
sa(k).b = rand;
end
Another option:
sb = struct('a', cell(1, 3), 'b', cell(1, 3));
% Now sb is a struct array of size [1, 3] with the empty fields a and b.
sb(1)
ans = struct with fields:
a: [] b: []
For the 2nd question: Your code is working, so what exactly are you asking for?
s.a = 1;
s.b = [1 2 3];
sa(1) = s
sa = 1×3 struct array with fields:
a b

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by