多维版本" kron"产品?

时间:2015-11-22 07:22:08

标签: matlab vectorization matrix-multiplication

现在我有一个维数N乘以p的矩阵A,另一个矩阵B的维数为N乘q。我想要的是一个矩阵,比如C,维度N乘以pq,这样

C(i,:) = kron(A(i,:), B(i,:));

如果N很大,则N行循环可能需要很长时间。因此,目前我正在适当地扩充A和B(结合使用 repmat 置换重塑)将每个矩阵的维数N转换为pq,然后用

之类的东西来制定C.
C = A_aug .* B_aug;

有更好的主意吗?

1 个答案:

答案 0 :(得分:2)

查看一些bsxfun + permute + reshape魔法 -

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

基准测试&验证

基准代码 -

%// Setup inputs
N = 200;
p = 190;
q = 180;
A = rand(N,p);
B = rand(N,q);

disp('--------------------------------------- Without magic')
tic
C = zeros(size(A,1),size(A,2)*size(B,2));
for i = 1:size(A,1)
    C(i,:) = kron(A(i,:), B(i,:));
end
toc

disp('--------------------------------------- With some magic')
tic
out = reshape(bsxfun(@times,permute(A,[1 3 2]),B),size(A,1),[]);
toc

error_val = max(abs(C(:)-out(:)))

输出 -

--------------------------------------- Without magic
Elapsed time is 0.524396 seconds.
--------------------------------------- With some magic
Elapsed time is 0.055082 seconds.
error_val =
     0