Clear Filters
Clear Filters

Matlab arrays preallocation techniques

2 views (last 30 days)
Giovanni Gardan
Giovanni Gardan on 25 May 2020
Commented: Stephen23 on 25 May 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 Comments
Giovanni Gardan
Giovanni Gardan on 25 May 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 on 25 May 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.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!