在MatLab中将矩阵的列与3d矩阵的2d矩阵切片相乘 [英] Multiply columns of a matrix with 2d matrix slices of a 3d matrix in MatLab

查看:76
本文介绍了在MatLab中将矩阵的列与3d矩阵的2d矩阵切片相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想执行以下计算:

Basically, I want to perform the following computation:

    G is m x n x k
    S is n x k

    Answer=zeros(m,d)
    for Index=1:k
        Answer(:,Index)=G(:,:,Index)*S(:,Index)
    end

因此,答案是一个矩阵,其列是将3d矩阵的每一层与另一个矩阵的列相乘的结果.

So, answer is a matrix, whose columns are the result of multiplying each layer of a 3d matrix with a column of another matrix.

这确实看起来像是一种简单的操作,我希望找出在Matlab中执行这种类型的计算是否有一种本机的或向量化的(或至少>>更快)的方式. 谢谢.

This really seems like a straightforward type of operation, and I was hoping to find out if there is a native or vectorized (or at least >> faster) way of performing this type of computation in Matlab. Thanks.

推荐答案

尝试使用 mtimesx .这是迄今为止我发现的最好的(快速/高效)工具,可以进行这种n维数组乘法,因为它使用了mex.我认为,您也可以使用 bsxfun ,但我的Matlab-fu不足以满足此类需求.

Try using mtimesx from the Matlab File Exchange. It's the best (fast/efficient) tool I've found so far to do this sort of n-dimensional array multiplication, since it uses mex . I think you could also use bsxfun, but my Matlab-fu is not enough for this sort of thing.

您有m x n x km x k,并且想要生成n x k.

You have m x n x k and m x k and want to produce a n x k.

mtimesxi x j x kj x r x k之类的输入相乘以生成i x r x k.

mtimesx multiplies inputs like i x j x k and j x r x k to produce i x r x k.

要将您的问题以mtimesx形式表示,请将G设为m x n x k,然后将S展开为n x 1 x k.然后mtimesx(G,S)将是m x 1 x k,然后可以将其展平到m x k.

To put your problem in mtimesx form, let G be m x n x k, and expand S to be n x 1 x k. Then mtimesx(G,S) would be m x 1 x k, which could then be flattened down to m x k.

m=3; 
n=4; 
k=2;
G=rand(m,n,k);
S=rand(n,k);

% reshape S
S2=reshape(S,n,1,k);

% do multiplication and flatten mx1xk to mxk
Ans_mtimesx = reshape(mtimesx(G,S2),m,k)

% try loop method to compare
Answer=zeros(m,k);
for Index=1:k
    Answer(:,Index)=G(:,:,Index)*S(:,Index);
end

% compare
norm(Ans_mtimesx-Answer)
% returns 0.

因此,如果您想要单线,您可以这样做:

So if you wanted a one-liner, you could do:

Ans = reshape(mtimesx(G,reshape(S,n,1,k)),m,k)

顺便说一句,如果您将问题发布在 Matlab新闻阅读器论坛上,有足够的专家比谁竞争给您比我更优雅或更有效的答案!

By the way, if you post your question on the Matlab Newsreader forums there'll be plenty of gurus who compete to give you answers more elegant or efficient than mine!

这篇关于在MatLab中将矩阵的列与3d矩阵的2d矩阵切片相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆