I stumbled upon the answer of Matt in a thread about creating identity matrices with Matlab. He uses
A(N,N) = 0
to allocate a NxN
matrix with zero entries. I've always used
A= zeros(N)
I was wondering, which of the two ways is faster and have written the following small test script.
function compare
N =2.^[1:14];
T1 = zeros(length(N),1);
for i=1:length(N)
clear A
n =N(i);
tic
A(n,n) = 0;
t=toc;
T1(i) = t;
end
T2 = zeros(length(N),1);
for i=1:length(N)
clear A
n =N(i);
tic
A=zeros(n);
t=toc;
T2(i) = t;
end
figure
loglog(N,T1,'r');
hold on
loglog(N,T2,'g');
title('Runtime for memory allocation');
legend('A(N,N)=0', 'A=zeros(N)','Location','SouthEast');
xlabel('N');
ylabel('Runtime')
end
Which simply measures the time for memory allocation via the two different ways. Here is the result:
This means, that for small N
, both methods are equally fast, but for N>1000
, the time to allocate a matrix with A(N,N)=0
actually drops? I'm unable to explain this result and would be happy to hear some opinions on this.
Thanks!