Array of Structures pre-allocation - code analyzer - appears to change size every loop iteration
4 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
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'.
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!