Nested Struct Preallocated Memory

3 views (last 30 days)
Chris
Chris on 9 Aug 2013
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

Accepted Answer

Jan
Jan on 9 Aug 2013
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.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!