/edit: See here for an interesting discussion of the topic. Thanks @Dan
Using a(m,n) = 0
appears to be faster, depending of the size of matrix a
, than a = zeros(m,n)
. Are both variants the same when it comes to pre-allocation before a loop?
/edit: See here for an interesting discussion of the topic. Thanks @Dan
Using a(m,n) = 0
appears to be faster, depending of the size of matrix a
, than a = zeros(m,n)
. Are both variants the same when it comes to pre-allocation before a loop?
They are definately not the same.
Though there are ways to beat the performance of a=zeros(m,n)
, simply doing a(m,n) = 0
is not a safe way to do it. If any entries in a
already exist they will keep existing.
See this for some nice options, also consider doing the loop backwards if you don't mind the risk.
I think it depends on your m and n. You can check the time for yourself
tic; b(2000,2000) = 0; toc;
Elapsed time is 0.004719 seconds.
tic; a = zeros(2000,2000); toc;
Elapsed time is 0.004399 seconds.
tic; a = zeros(2,2); toc;
Elapsed time is 0.000030 seconds.
tic; b(2,2) = 0; toc;
Elapsed time is 0.000023 seconds.