Why is diag faster than zeros?
Show older comments
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
Walter Roberson
on 24 Sep 2013
Did you cross-check with timeit() from the FEX ? With two different functions? It is possible that time is being mis-accounted .
Peter
on 24 Sep 2013
Accepted Answer
More Answers (1)
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 Matrix Indexing 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!