Code covered by the BSD License  

Highlights from
kronecker

5.0

5.0 | 3 ratings Rate this file 3 Downloads (last 30 days) File Size: 1.86 KB File ID: #24499

kronecker

by Bruno Luong

 

21 Jun 2009 (Updated 22 Jun 2009)

Kronecker tensor product

| Watch this File

File Information
Description

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:

clear,
gain=[];
mem = memory;
maxn = (mem.MaxPossibleArrayBytes/32)^0.25;
n = 10:10:maxn;
for sz=n
    A=rand(sz); B=rand(sz);
    t1=Inf;
    for ntry=1:10
        tic; K = kron(A,B); t1=min(t1,toc);
    end
    clear K
    t2=Inf;
    for ntry=1:10
        tic; K = kronecker(A,B); t2=min(t2,toc);
    end
    clear K
    gain(end+1) = t1/t2;
end

fprintf('Size A/B Speed gain\n');
fprintf(' %02d %1.2f \n', [n; gain]);

    Size A/B Speed gain
       10 1.17
       20 3.48
       30 3.78
       40 3.73
       50 3.68
       60 4.22
       70 3.81

Acknowledgements
This submission has inspired the following:
Kronecker product
MATLAB release MATLAB 7.4 (R2007a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (7)
23 Jun 2009 Mayowa

Hi,

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)
  [ra, ca]=size(a);
  [rb, cb]=size(b);
  c = a(ones(rb,1)*(1:ra), ones(cb,1)*(1:ca)).* b((1:rb)'*ones(1,ra), (1:cb)'*ones(1,ca));
  

24 Jun 2009 Matt Fig

Mayowa,

Indeed that is faster for smaller A,B. However, for larger A and B, kronecker is several times faster.

24 Jun 2009 Matt Fig

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.

25 Jun 2009 Bruno Luong

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);

25 Jun 2009 Matt Fig

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.

25 Jun 2009 Mayowa  
18 Jul 2009 Minchul Shin  
Please login to add a comment or rating.
Updates
22 Jun 2009

Miss spelling corrected

Tag Activity for this File
Tag Applied By Date/Time
kron Bruno Luong 22 Jun 2009 11:16:15
kronecker Bruno Luong 22 Jun 2009 12:22:35

Contact us at files@mathworks.com