Nested Struct Preallocated Memory

5 次查看(过去 30 天)
Good Day,
What is the best way to preallocate for a nested struct? I'm currently looping as follows but looking around it doesn't seem the way to go:
for i = 1:n
for j = 1:x
Field.SubField(i).Element(j).X = zeros(3,1)
Field.SubField(i).Element(j).Y = zeros(3,1)
Field.SubField(i).Element(j).Z = zeros(3,1)
end
end

采纳的回答

Jan
Jan 2013-8-9
With the shown method, the array Field.SubField and Field.SubField(i).Element still grow in each iteration. So a pre-allocate happens for the fields X, Y, Z only. Better:
for i = n:-1:1 % Backwards for implicit pre-allocation!
for j = x:-1:1 % Backwards for implicit pre-allocation!
Field.SubField(i).Element(j).X = zeros(3,1)
Field.SubField(i).Element(j).Y = zeros(3,1)
Field.SubField(i).Element(j).Z = zeros(3,1)
end
end
If in the first iteration Field.SubField(n).Element(x) is created, and this creates Field.SubField(1) and Field.SubField(n).Element(1) implicitly also.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by