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

9 ビュー (過去 30 日間)
Ben
Ben 2013 年 6 月 13 日
回答済み: Rishabh Rathore 2018 年 5 月 23 日
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

回答 (1 件)

Rishabh Rathore
Rishabh Rathore 2018 年 5 月 23 日
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'.

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by