array of structs how to preallocate and assign

86 次查看(过去 30 天)
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;

回答(1 个)

Jan
Jan 2021-9-6
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

类别

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