array of structs how to preallocate and assign

135 ビュー (過去 30 日間)
Leos Pohl
Leos Pohl 2021 年 9 月 6 日
回答済み: Jan 2021 年 9 月 6 日
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 Center および File ExchangeStructures についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by