Matlab arrays preallocation techniques

1 visualizzazione (ultimi 30 giorni)
Giovanni Gardan
Giovanni Gardan il 25 Mag 2020
Commentato: Stephen23 il 25 Mag 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 Commenti
Giovanni Gardan
Giovanni Gardan il 25 Mag 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 il 25 Mag 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.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by