Array of Structures pre-allocation - code analyzer - appears to change size every loop iteration
조회 수: 4 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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'.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!