I use 64-bit Matlab R2014b.
I have a large matrix in which I iteratively change one element and I have another operation in which I sort a smaller matrix. I have two minimal working examples and I would like to know why one approach takes longer than the other. The first example uses a direct approach, whereas the second approach uses a function to perform the task.
Minimal working example 1
n_iter = 1e7; A = zeros(n_iter,1); B = sort(rand(1e3,1)); for i = 1:n_iter A(i) = 1; B = sort([ B(2:end); B(1) ]); end
Minimal working example 2
function deallocating_large_matrices_function n_iter = 1e7; A = zeros(n_iter,1); B = sort(rand(1e3,1)); for i = 1:n_iter A(i) = 1; B = sortB(B(2:end),B(1)); end end function B = sortB(B,new_entry) B = sort([ B ; new_entry ]); end
Results
Below a table showing the time it took to run both examples as a function of n_iter, using the profiler.
n_iter | time MWE 1 (sec) | time MWE 2 (sec) -------------------------------------------- 1e4 | 0.13 | 0.21 1e5 | 1.38 | 1.98 1e6 | 13.5 | 19.7 1e7 | 137 | 196
The time it takes to run both MWE 1 and MWE2 increases linearly. Running MWE 2 takes approximately 46% more time. What is the cause of this increase?
Best Answer