Why is diag faster than zeros?

I get some surprising timings when i allocate a zero matrix using zeros and diag. For instance when i run the code:
N = 10000;
tic
A = diag(zeros(1,N));
toc
tic
B = zeros(N);
toc
I get the output:
Elapsed time is 0.007424 seconds.
Elapsed time is 0.181349 seconds.
Suggesting that that it should be 24 times faster to allocate using a zero diagonal diag comapred to just using zeros. I find this very weird so I was wondering if someone could explain/educate me on what is happening? :)
Thanks,
Peter

2 Comments

Did you cross-check with timeit() from the FEX ? With two different functions? It is possible that time is being mis-accounted .
I do not know about timeit(), but using cputime i get a similar result only know the factor is only 3-4.

Sign in to comment.

 Accepted Answer

James Tursa
James Tursa on 24 Sep 2013
Edited: James Tursa on 24 Sep 2013
More discussion related to this can be found on this thread:
There is no documentation on how the various functions and operations allocate variables, but the guess is that some functions and operations draw from a pool of previously zero'ed out memory while others don't, hence the timing differences.

More Answers (1)

Jan
Jan on 24 Sep 2013
Edited: Jan on 24 Sep 2013
The JIT acceleration can eliminate dead code. So please try:
N = 10000;
tic
for k = 1:100
A = diag(zeros(1,N));
A(1) = 1;
clear('A');
end
toc
tic
for k = 1:100
B = zeros(N);
B(1) = 1;
clear('B');
end
toc
Now copy this inside a function M-file and compare the times again.
Dummy loops do not reflect the behavior in a real program necessarily.

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!