You can overcome the problem by pre-allocating the array of structures as follows:
clear all;
N = 10;
structArray1(N) = struct('field1',[], 'field2',[], 'field3',[]);
for i=1:N
field1 = "field1";
field2 = "field2";
field3 = "field3";
structArray1(i)=getStruct(field1, field2,field3);
end
Alternatively, instead of pre-allocating before the loop, you can also loop backwards so that all the memory allocation is done in the first iteration itself.
N = 10;
for i=N:-1:1
field1 = "field1";
field2 = "field2";
field3 = "field3";
structArray2(i)=getStruct(field1, field2,field3);
end
structArray2 = fliplr(structArray2);
The getStruct function is as follows:
function outStruct = getStruct(field1, field2,field3)
outStruct.field1 = field1;
outStruct.field2 = field2;
outStruct.field3 = field3;
end
Best Answer