简体   繁体   English

在MATLAB中将每个子块与矩阵相乘

[英]Multiply each sub-block with a matrix in MATLAB

I would like to multiply each sub-block of a matrix A mxn with a matrix B pxq. 我想将矩阵A mxn的每个子块与矩阵B pxq相乘。 For example A can be divided into k sub blocks each one of size mxp. 例如,可以将A分为k个子块,每个子块的大小为mxp。

A = [A_1 A_2 ... A_k] A = [A_1 A_2 ... A_k]

The resulting matrix will be C = [A_1*B A_2*B ... A_k*B] and I would like to do it efficiently. 结果矩阵将为C = [A_1 * B A_2 * B ... A_k * B],我想高效地做到这一点。

What I have tried until now is: 到目前为止,我尝试过的是:

C = A*kron(eye(k),B) C = A * kron(eye(k),B)

Edited: Daniel I think you are right. 编辑:丹尼尔我认为你是对的。 I tried 3 different ways. 我尝试了3种不同的方式。 Computing a kronecker product seems to be a bad idea. 计算kronecker产品似乎不是一个好主意。 Even the solution with the reshape works faster than the more compact kron solution. 甚至具有重塑形状的解决方案也比更紧凑的kron解决方案更快地工作。

tic 
for i=1:k
C1(:,(i-1)*q+1:i*q) = A(:,(i-1)*p+1:i*p)*B;
end
toc

tic
C2 = A*kron(eye(k),B);
toc

tic
A = reshape(permute(reshape(A,m,p,[]),[1 3 2]),m*k,[]);
C3 = A*B;
C3 = reshape(permute(reshape(C3,m,k,[]),[1 3 2]),m,[]);
toc

When I look at your matrix multiplication code, you have perfectly optimized code within the loop. 当我看您的矩阵乘法代码时,您在循环中有经过优化的代码。 You can't beat matrix multiplication. 您不能击败矩阵乘法。 Everything you could cut down is the overhead for the iteration, but compared to the long runtime of a matrix multiplication the overhead has absolutely no influence. 您可以削减的一切只是迭代的开销,但是与矩阵乘法的长时间运行相比,开销绝对没有影响。

What you attempted to do would be the right strategy when the operation within the loop is trivial but the loop is iterated many times. 当循环中的操作微不足道但循环被多次迭代时,您尝试做的事情就是正确的策略。 If you take the following parameters, you will notice that your permute solution has actually it's strength, but not for your problem dimensions: 如果采用以下参数,您会注意到permute解决方案实际上具有优势,但不适用于您的问题范围:

q=1;p=1;n=1;m=1;
k=10^6

Kron totally fails. 克朗完全失败了。 Your permute solution takes 0.006s while the loop takes 1.512s 您的置换解决方案需要0.006s而循环需要1.512s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM