Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate Kronecker tensor with repmat in MATLAB

I am trying to replicate the Kron product using only repmat and reshape and I believe I am pretty close but I can't manage to do the last correct reshape. Particularly I have problem in reshaping A

To make things simple let suppose we have

A=[1 3; 2 4]
B=[5 10; 10 5]

so my kron(A,B) is going to be a 4x4 matrix.

kron=[5   10  15  30
      10  5   30  15
      10  20  20  40
      20  10  40  20]

I am proceeding this way:

Y=repmat(B,2,2)
X=A(:);
X=repmat(X,1,2)';
X=X(:);
X=repmat(X,1,2);

which gives me the following 8x2 Matrix:

X= [1 1
    1 1 
    2 2
    2 2
    3 3
    3 3
    4 4
    4 4]

I can't just figure out how to do the correct reshape to obtain my 4x4 matrix:

X=[1 1 3 3
   1 1 3 3
   2 2 4 4
   2 2 4 4]

Then I will be able to compute: X.*Y=kron(A,B)

like image 604
CAPSLOCK Avatar asked Oct 15 '15 12:10

CAPSLOCK


2 Answers

Here's one approach using the powerful trio of bsxfun, permute and reshape -

M = bsxfun(@times,B,permute(A,[3 4 1 2]));
out = reshape(permute(M,[1 3 2 4]),size(A,1)*size(B,1),[]);

If you are hell bent on using repmat, perform the calculation of M with it, like so -

M = repmat(B,[1 1 size(A)]).*permute(repmat(A,[1 1 size(B)]),[3 4 1 2])

Verify output by comparing against kron for generic matrix sizes -

>> A = rand(4,5);
>> B = rand(6,7);
>> M = bsxfun(@times,B,permute(A,[3 4 1 2]));
>> out = reshape(permute(M,[1 3 2 4]),size(A,1)*size(B,1),[]);
>> out_kron = kron(A,B);
>> max(abs(out(:) - out_kron(:)))
ans =
     0

Here's one using matrix-multiplication and as such must be pretty efficient -

[mA,nA] = size(A);
[mB,nB] = size(B);
out = reshape(permute(reshape(B(:)*A(:).',mB,nB,mA,nA),[1 3 2 4]),mA*mB,[])
like image 95
Divakar Avatar answered Nov 17 '22 00:11

Divakar


If you don't want to use any loops or bsxfun/arrayfun-solutions, you can do as follows:

[ma,na] = size(A);
[mb,nb] = size(B);
Y = repmat(B,ma,mb);
X = reshape(repmat(reshape(repmat(A(:),1,mb)',ma*mb,na),nb,1),ma*mb,na*nb);
X.*Y
like image 3
Jens Boldsen Avatar answered Nov 16 '22 23:11

Jens Boldsen