array of structs how to preallocate and assign

조회 수: 143 (최근 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 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