Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

memory management - MATLAB : Appending to pre-allocated matrix

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];).

Pre-allocation

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:

Automatic Array Growth Optimization

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...