フィルターのクリア

Matlab arrays preallocation techniques

2 ビュー (過去 30 日間)
Giovanni Gardan
Giovanni Gardan 2020 年 5 月 25 日
コメント済み: Stephen23 2020 年 5 月 25 日
I'm trying to make my code faster to run. In literature, one of technique is preallocating arrays used in the code.
Let's suppose we have a 1000x1000 matrix to pre-allocate before a while loop. It is known that sparse form save memory, but save also time?
Which of the following two options is better?
%First way
A = zeros(1000);
%Second way
A = sparse(1000);
  3 件のコメント
Giovanni Gardan
Giovanni Gardan 2020 年 5 月 25 日
Thank you for the answer.
Yes you are right, but seems like in some cases the first way is faster, in other cases the secondo way is faster. I'd like to know if there is a general rule to treat preallocation
Stephen23
Stephen23 2020 年 5 月 25 日
In general adding new data to sparse arrays is slow. Rather than preallocating the entire sparse array the usual efficient approach is to build up vectors of the indices and the data in the loop and after the loop convert them to sparse.
Your array is not very large I doubt that there is much point in defining it as sparse anyway.

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

回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by