每行乘积的总和 [英] Sum of product each row by a matrix

查看:97
本文介绍了每行乘积的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵A和一个3维矩阵B.我想总结(按i)

I have a matrix A and a three-dims matrix B. I want to sum (by i)

A(i,:)*B(i,:,:)

但没有i的循环.

推荐答案

我将首先创建一些类似于您所描述的随机矩阵:

I'll start by creating some random matrices similar to what you described:

n = 4; m =3;
A = rand(n,m);
B = rand(n,m,5);

1)循环版本:

C = zeros(1,size(B,3));
for i=1:n
    C = C + A(i,:)*squeeze(B(i,:,:));
end

基本上,它对A的每一行与B的相应切片进行矩阵相乘,并累加和.

basically it performs matrix multiplication of each row of A by the corresponding slice of B, and accumulates the sum.

可以通过在循环外对矩阵B进行一次排列来稍微改善它,从而避免多次调用squeeze ...

This is could be slighty improved by permuting the matrix B once outside the loop, thus avoiding the multiple calls to squeeze...

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

我没有声称这应该更快.实际上,我怀疑循环版本既更快又占用更少的内存.

I don't make any claims that this should be faster. In fact I suspect the looped version to be both faster and less memory intensive.

我将留给您比较使用实际尺寸的两者.

I'll leave it to you to compare the two using the actual dimensions are working with.

这篇关于每行乘积的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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