MATLAB 变量''似乎会随迭代次数而改变,请预分配内存以2获得更高的运算速度

在MATLAB的help文件中可以找到如下说明:

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.

大概意思是:for和while循环每次循环时递增地增加数据结构的大小会对性能和内存使用产生负面影响。 重复调整数组大小通常需要MATLAB®花费额外的时间来寻找更大的连续内存块,然后将数组移动到这些块中。 通常,您可以通过预分配阵列所需的最大空间来缩短代码执行时间。

解决办法:使用zeros函数

代码1:

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

运行输出:Elapsed time is 0.301528 seconds.

代码2:

tic
x = zeros(1, 1000000);
for k = 2:1000000
   x(k) = x(k-1) + 5;
end
toc
运行输出:Elapsed time is 0.011938 seconds.

可见运算的速度有明显的提高

 

你可能感兴趣的:(MATLAB,MATLAB)