Why is diag faster than zeros?
Mostrar comentarios más antiguos
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 comentarios
Walter Roberson
el 24 de Sept. de 2013
Did you cross-check with timeit() from the FEX ? With two different functions? It is possible that time is being mis-accounted .
Peter
el 24 de Sept. de 2013
Respuesta aceptada
Más respuestas (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.
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!