array of structs how to preallocate and assign

81 views (last 30 days)
Leos Pohl
Leos Pohl on 6 Sep 2021
Answered: Jan on 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;

Answers (1)

Jan
Jan on 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

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!