preallocate vector or not

9 ビュー (過去 30 日間)
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 9 月 22 日
I'm doing a simulation and I initialize a vector that will contain during the simulation integer values. At the beginning I don't know its length so I can't initialize it to any value but I initialize it in this way:
vector = [];
as empty vector Starting my simulation integer values will be added depending on the results of this simulation. Matlab return me a suggestion to preallocate it for speed. This way it's correct or there is another way to do ?

回答 (3 件)

Thomas
Thomas 2012 年 9 月 22 日
編集済み: Thomas 2012 年 9 月 22 日
Preallocation helps speed up code and reduces memory fragmentation..
The following link will help you understand how..
Another good link on improving speed..

José-Luis
José-Luis 2012 年 9 月 22 日
編集済み: José-Luis 2012 年 9 月 22 日
You should preallocate for speed, just try:
numVals = 10^5;
noAlloc = [];
Alloc = NaN * ones(numVals,1);
tic
for ii = 1:numVals
noAlloc = [noAlloc 1];
end
toc
tic
for ii = 1:numVals
Alloc(ii) = 1;
end
toc
I get:
Elapsed time is 10.128797 seconds. (No allocation)
Elapsed time is 0.000335 seconds. (Pre-allocation)
A difference of four orders of magnitude. I would recommend to allocate a vector as large as you think you might need, and then save your values in it, something like:
your_res = NaN * ones(reasonable_val,1);
counter = 1;
for ii = 1:your_simulations
if you_get_result
your_res(counter) = your_val;
counter = counter + 1;
if counter > reasonable_val %You could skip this, but it will return an error if counter > reasonable_val
your_res = [your_res; NaN*ones(reasonable_val,1)];
end
end
end
your_res(counter:end) = [];
Alternatively, a cell array does not require contiguous memory allocation (well, all elements inside a cell are in contiguous memory locations), so it might be a (slower) alternative to your problem, as it does not require reallocating your array if it overruns an empty memory block.
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 22 日
編集済み: Azzi Abdelmalek 2012 年 9 月 22 日
not fair comparison, why
noAlloc = [noAlloc 1]
and not
Alloc(ii) = 1
Elapsed time is 0.058491 seconds.
Elapsed time is 0.010952 seconds.
José-Luis
José-Luis 2012 年 9 月 22 日
Because that's how I understood how Salvatore intended to build his results matrix.

サインインしてコメントする。


Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 22 日
I think, if you have an idea about your vector size, your code will be faster, if you preallocate:
A=zeros(1,m) % for example

カテゴリ

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