MATLAB:追加到预先分配的矩阵 [英] MATLAB : Appending to pre-allocated matrix

查看:263
本文介绍了MATLAB:追加到预先分配的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些mxn矩阵的MATLAB代码.
最初,我将第一行放入其中,然后代码通过for循环运行,该循环将剩余的m-1行一个接一个地追加;每个循环迭代一次.
不出所料,MATLAB建议我预先分配矩阵,因为矩阵会随着循环的每次迭代而扩展. 因此,如果我在所有m行中都预先分配了零,则MATLAB很可能会在m行之后添加行(从m + 1开始为第一个附加行),因为m行已经被填充(即使有零!)
在这种情况下,是否有任何预分配矩阵的方法可以提高速度?

I have some MATLAB code with mxn matrix.
Initially, I put first row in it and then the code runs through a for loop which appends remaining m-1 rows one by one; one for each iteration of the loop.
As expected, MATLAB recommends me to pre-allocate the matrix because it is expanding with every iteration of loop. So, if I pre-allocate zeros in all m rows, MATLAB most probably will append rows after the m rows(starting from m+1 for 1st appended row) because m rows are already filled(even though with zeros!)
Is there any way of pre-allocating matrix in this scenario for improving speed?

推荐答案

您不能在不更改MATLAB大小的情况下预先分配它,至少不能手动更改它的大小.但是,MATLAB在最新版本中大大提高了自动数组增长的性能,因此您可能不会看到巨大的性能影响.尽管如此,最佳实践还是使用zeros预先分配数组,并使用A(i,:) = rowVec;索引行,而不是附加行(A = [A; rowVec];).

You cannot pre-allocate a MATLAB array without also changing it's size, at least not manually. However, MATLAB has improved automatic array growth performance a lot in recent versions, so you might not see a huge performance hit. Still, best practice would be to pre-allocate your array with zeros and index the rows with A(i,:) = rowVec; instead of appending a row (A = [A; rowVec];).

如果您确定要充分利用MATLAB的性能,Yair Altman上有几篇关于内存预分配的出色文章:

If you are determined to squeeze every bit of performance out of MATLAB, Yair Altman has a couple of excellent articles on the topic of memory pre-allocation:

  • Preallocation performance
  • Preallocation performance and multithreading

如果您真的想通过沿维度增长来使用动态数组大小调整,则有一些方法可以正确执行.请参见 Steve Eddins撰写的MathWorks博客文章.需要注意的最重要的事情是,您应该沿着最后一个维度增长以获得最佳性能. (即在您的情况下添加列). Yair还在他博客上的另一篇文章中讨论了动态数组调整大小.

If you really want to use dynamic array resizing by growing along a dimension, there are ways to do it right. See this this MathWorks blog post by Steve Eddins. The most important thing to note is that you should grow along the last dimension for best performance. (i.e. add columns in your case). Yair also discusses dynamic array resizing in another post on his blog.

此外,还有一些无需初始化即可使用一些毛茸茸的MEX API杂技来分配数组的方法,仅此而已.

Also, there are ways of allocating an array without initializing using some hairy MEX API acrobatics, but that's it.

这篇关于MATLAB:追加到预先分配的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆