Vectorize the pairwise kronecker product in matlab

我怕爱的太早我们不能终老 提交于 2019-12-23 12:37:18

问题


Suppose there are two matrices of the same size, and I want to calculate the summation of their column-wise kronecker product. Due to sometimes the column size is quite large so that the speed could be very slow. Thus, is there anyway to vectorize this function or any function may help reducing the complexity in matlab? Thanks in advance.

The corresponding matlab code with a for-loop is provided below, and the answer of d is the interested output:

A = rand(3,7);
B = rand(3,7);
d = zeros(size(A,1)*size(B,1),1);
for i=1:size(A,2)
    d = d + kron(A(:,i),B(:,i));
end

回答1:


Using the rewriting of the Kronecker product given by Daniels answer

e=zeros(size(B,1),size(A,1));
for i=1:size(A,2)
    e = e + B(:,i)*A(:,i).';
end
e=reshape(e,[],1);

we say that

C = A'

and thus

for i=1:m
    e = e + B(:,i)*C(i,:);
end

which is the definition of the matrix product

B*C.

In conclusion the problem can thus be solved by the simple matrix product

d = reshape(B*A',[],1);



回答2:


The kronecker product of two vectors is just a reshaped result of the matrix multiplication of both vectors:

e=zeros(size(B,1),size(A,1));
for i=1:size(A,2)
    e = e + B(:,i)*A(:,i).';
end
e=reshape(e,[],1);

Now knowing that it's just a sum of products, it can be put into a single line using bsxfun

f=reshape(sum(bsxfun(@times,permute(B,[1,3,2]),permute(A,[3,1,2])),3),[],1);

Depending on the input, the bsxfun-sulution is slightly faster than the matrix multiplication, but that comes with a high memory consumption. The bsxfun-solution uses O(size(A,1)*size(B,1)*size(B,2)) while the for-loop only uses O(size(A,1)*size(B,1)) in addition to the input arguments.



来源:https://stackoverflow.com/questions/32280002/vectorize-the-pairwise-kronecker-product-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!