This function does exactly what Matlab KRON does, but for large full matrices, the engine uses BSXFUN to accelerate the calculation.
Another advantage is no intermediate large matrices are generated (four temporary arrays in case of KRON).
Here is the benchmark code and result:
mem = memory;
maxn = (mem.MaxPossibleArrayBytes/32)^0.25;
n = 10:10:maxn;
tic; K = kron(A,B); t1=min(t1,toc);
tic; K = kronecker(A,B); t2=min(t2,toc);
gain(end+1) = t1/t2;
fprintf('Size A/B Speed gain\n');
fprintf(' %02d %1.2f \n', [n; gain]);
Size A/B Speed gain
Congratulating in having your efficient code incorporated in the stock KRON function in R2013b - well done, Bruno!
Fast, slick, well done.
Thanks for answering my question. I was waiting on that in order to give a rating, now I know it is my old (!, 2007b) version of MATLAB which is out of alignment.
To Matt's comment #2: 2D error checking is introduced in KRON in recent Matlab version. KORNECKER is designed to replicate the same behavior (desirable?).
A workaround (beside delete the error checing line) is:
A = reshape(A,size(A,1),);
B = reshape(B,size(B,1),);
C = kronecker(A,B);
My only question is why the function errors out for non- 2D inputs? The stock MATLAB function does not error, and if I take the offending lines of code out of kronecker, the results match.
Indeed that is faster for smaller A,B. However, for larger A and B, kronecker is several times faster.
I found a faster implementaion here
http://ftp.icm.edu.pl/packages/octave/MAILING-LISTS/octave-sources/1999/77. I have translated it into matlab below
function c = kron2(a,b)
c = a(ones(rb,1)*(1:ra), ones(cb,1)*(1:ca)).* b((1:rb)'*ones(1,ra), (1:cb)'*ones(1,ca));
Miss spelling corrected