I've stumbled upon the weird way (in my view) that Matlab is dealing with empty matrices. For example, if two empty matrices are multiplied the result is:
zeros(3,0)*zeros(0,3) ans = 0 0 0 0 0 0 0 0 0
Now, this already took me by surprise, however, a quick search got me to the link http://www.mathworks.com/help/matlab/math/empty-matrices-scalars-and-vectors.html , and I got an explanation of the somewhat twisted logic of why this is happening.
However, nothing prepared me for the following observation. I asked myself, how efficient is this type of multiplication vs just using zeros(n) function, say for the purpose of initialization? I've used timeit to answer this:
f=@() zeros(1000) timeit(f) ans = 0.0033
vs:
g=@() zeros(1000,0)*zeros(0,1000) timeit(g) ans = 9.2048e-06
Both have the same outcome of 1000×1000 matrix of zeros of class `double`, but the empty matrix multiplication one is ~350 times faster! (a similar result happens using `tic` and `toc` and a loop)
How can this be? are `timeit` or `tic,toc` bluffing or have I found a faster way to initialize matrices?
(this was done with matlab 2012a, on a win7-64 machine, intel-i5 650 3.2Ghz…)
I have looked more carefully into this peculiarity, and tested on 2 different computers (same matlab ver though 2012a) a code that examine the run time vs the size of matrix n. This is what I get:
The code to generate this used timeit as before, but a loop with tic and toc will look the same. So, for small sizes, zeros(n) is comparable. However, around n=400 there is a jump in performance for the empty matrix multiplication. The code I've used to generate that plot was:
n=unique(round(logspace(0,4,200))); for k=1:length(n) f=@() zeros(n(k)); t1(k)=timeit(f); g=@() zeros(n(k),0)*zeros(0,n(k)); t2(k)=timeit(g); end loglog(n,t1,'b',n,t2,'r'); legend('zeros(n)','zeros(n,0)*zeros(0,n)',2); xlabel('matrix size (n)'); ylabel('time [sec]');
Are any of you seeing anything similar?
Best Answer