Kronecker tensor replication with rep in MATLAB

I am trying to replicate a Kron product using only repmat and reshape, and I find myself pretty close, but I cannot make the last correct change. In particular, I have a problem with rebuilding A

To make things simple, suppose that

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

therefore my kron(A,B) will be a 4x4 matrix.

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

I continue:

 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 make the right change to get my 4x4 matrix:

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

Then I can calculate: X.*Y=kron(A,B)

+5
source share
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 damn tuned to use repmat , do an M calculation with it, for example:

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

Check output by comparing with kron for total 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 matrix-multiplication and as such should be quite 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,[]) 
+4
source

If you do not want to use any loops or bsxfun / arrayfun -solutions, you can do the following:

 [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 
+3
source

Source: https://habr.com/ru/post/1233781/


All Articles