MATLAB: Nested Struct Preallocated Memory

preallocate memory nested struct

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

Best Answer

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.