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.

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

 

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值