Preallocating memory for a matrix of unknown size

39 ビュー (過去 30 日間)
Simon
Simon 2013 年 6 月 24 日
回答済み: Zhiyu Xiao 2019 年 4 月 18 日
I have a number of points I need to store in a matrix - an m*2 to be specific. The problem being I do not know how many I need to store beforehand, but it typically ranges from 1500 - 15000. Is there a more efficient way of allocating memory than just using an arbitrarily big size that I know will definitely fit everything, or should I increment the matrix size by 1 with every step? theoretically I could run the code once before and just count the number of points, but I wont do that, because the code is too slow already.
So what's the best way to to this?

採用された回答

Iain
Iain 2013 年 6 月 24 日
At what point do you know the required size?
If it's "at the end", then you do have to do with the "arbitrarily big" option, but you can do that piece-wise. You can preallocate, say, 5000, and when you get to 5001, allocate an extra 5000...
If it's at "some defined point in my code", you can allocate at that point.
Alternatively, you could not store the results in RAM, if it's an issue, you should consider writing a file and popping each pair of values in.

その他の回答 (3 件)

Hugo
Hugo 2013 年 6 月 24 日
You can use a buffer. I mean, suppose the matrix you want is M, then create M=[]; and a vector X=zeros(xsize,2), where xsize is a relatively small value compared with m (the number of rows of M). Then, fill X and when it is filled, just concatenate the matrix with M by doing M=[M; X]; and start filling X again from the first row on. That should save some time.

Simon
Simon 2013 年 6 月 24 日
Ah. Good id. Thanks guys

Zhiyu Xiao
Zhiyu Xiao 2019 年 4 月 18 日

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by