Matlab2017a版本,编写for循环程序时,经常提示对变量进行preallocation memory(预设内存)的提示,在matlab自带帮助文档中,有如下具体解释,同时提供了实例:用zeros或ones函数预定义变量。
forandwhileloops that incrementally increase the size of a data structure each time through the loop can adversely affect performance and memory use. Repeatedlyresizing arraysoften requires MATLAB®to spend extra time looking forlarger 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.
The following code displays the amount of time needed to create a scalar variable,x, and then to gradually increase the size ofxin aforloop.
ticx = 0;for k = 2:1000000 x(k) = x(k-1) + 5;endtoc
Elapsed time is 0.301528 seconds.
If you preallocate a 1-by-1,000,000 block of memory forxand initialize it to zero, then the code ru