MATLAB variable '' seems to vary with the number of iterations, please pre-allocated memory to obtain higher operation speed 2

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/u013215852/article/details/92977405

The following description can be found in the MATLAB help file:

for and while loops that incrementally increase the size of a data structure each time through the loop can adversely affect performance and memory use. Repeatedly resizing arrays often requires MATLAB® to spend extra time looking for larger contiguous blocks of memory, and then moving the array into those blocks. Often, you can improve code execution time by preallocating the maximum amount of space required for the array.

Probably it means: for and while loops will increase the size of each performance and memory usage data structures incrementally adversely affect the cycle. Repeat MATLAB® resize the array generally requires additional time to find a larger contiguous memory block, then these blocks move to the array. Typically, the maximum space You can be shortened by a pre-allocated array of code execution time.

Solution: Use the zeros function

Code 1:

tic
x = 0;
for k = 2:1000000
   x(k) = x(k-1) + 5;
end
toc

Run output: Elapsed time is 0.301528 seconds.

Code 2:

TiC
X = zeros (. 1, 1000000);
for K = 2: 1000000
   X (K) = X (. 1-K) +. 5;
End
TOC
run output: Elapsed time is 0.011938 seconds.

Visible calculation speed significantly improved

 

Guess you like

Origin blog.csdn.net/u013215852/article/details/92977405