Array of Structures pre-allocation - code analyzer - appears to change size every loop iteration

9 views (last 30 days)
In each for loop below, the code analyzer gives a warning that the "variable 'x' appears to change size on every loop". Is this not the proper way to pre-allocate and array of structures? There is definitely a difference in execution time between the pre-allocated and the not pre-allocated loops.
%This code is for demonstration of the problem
loops = 2000000; %number of iterations
tic
x.tt = 1; %create structure
x.gg = 2;
x(loops).tt = 1; %pre-allocate array of structures
for j=1:loops
x(j).tt = 1; %loop through pre-allocated structure
end
toc %pre-allocated time
clear x j; %delete variables
tic
x.tt = 1; %create structure
x.gg = 2;
for j=1:loops
x(j).tt = 1; %loop through structure (not pre-allocated)
end
toc %not pre-allocated time

Answers (1)

Rishabh Rathore
Rishabh Rathore on 23 May 2018
The reason behind is that you cleared the array x before running the second loop and the pre-allocation before second loop only created a scaler, not an array( size=[1 1]) of size 'loops'.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!