Filter löschen
Filter löschen

Matlab arrays preallocation techniques

2 Ansichten (letzte 30 Tage)
Giovanni Gardan
Giovanni Gardan am 25 Mai 2020
Kommentiert: Stephen23 am 25 Mai 2020
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 Kommentare
Giovanni Gardan
Giovanni Gardan am 25 Mai 2020
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 am 25 Mai 2020
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.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by