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

10 visualizzazioni (ultimi 30 giorni)
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

Risposte (1)

Rishabh Rathore
Rishabh Rathore il 23 Mag 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'.

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by