Preallocating Memory in Matlab
It's probably something that most of you already know but since there are a beginners here too, I thought I'll brief on this topic.
I found this trick particularly useful when dealing with large arrays whose value is based on previous values. Saves tonnes of time in computation.
Start with a(1) = 1
a(2) = a(1) + 2
a(3) = a(2) + 3 and so on.
tic a = 1; for i = 2:100000 a(i,1) = a(i-1,1) + i; end toc
Elapsed time is 22.234634 seconds.
Tweak the code a bit by preallocating space to memory:
tic a = ones(100000,1); % You are preallocating 100000 rows of value 1 to memory for computation in matlab for i = 2:100000 a(i,1) = a(i-1,1) + i; end toc
Elapsed time is 0.001953 seconds.
Ratio of Computation Duration:
|efficient coding, matlab, preallocating|