如何在矢量化MATLAB这个矩阵乘法 [英] How to vectorize this matrix multiplication in matlab

查看:317
本文介绍了如何在矢量化MATLAB这个矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2矩阵A(n×m个)和B(NXD),想乘的元素明智的有<罢工>的一排A的每一列 B.有m B中的A柱和n 1XD载体这样的成绩分别为m NXD矩阵。然后我想总结(result_i,1)把米1XD载体,我想申请vertcat获得MXD矩阵。我做使用循环作业本,它是缓慢的,因为n和d为大。我怎样才能在MATLAB这个矢量化,使其更快?谢谢。

编辑:结果
你没事吧:我被我自己的问题混为一谈。我的意思是相乘的元素明智的有B的A行中的每一列,就是要乘N的一列的元素与B对应的n行我想用什么作为一个跟随的一列(我重复此为A的m列,那么vertcat的C的矢量合力得到一个MXD矩阵):

  column_of_A =     3
     3
     1
B =     3 1 3 3
     2 2 1 2
     1 3 3 3
C = SUM(诊断(column_of_A)* B,1)     16 12 15 18


解决方案

您可以向量化你的操作方法如下:但是请注意,该量化正值更高的内存使用成本,因此该解决方案最终可能会不为你工作。

 %#n×m个乘法与一个nx1xd B到创建nxmxd阵列
TMP = bsxfun(@倍,A,置换(B,[1 3 2]));%#总和,变成MXD
OUT =挤压(SUM(TMP,1));

您可能想在一行中做的一切,这可能有助于Matlab的JIT编译器,以节省内存。

修改

下面是,以取代第一行,如果你没有办法 bsxfun

  [N,M] =尺寸(A);
[N,D] =尺寸(B);
TMP = repmat(A,[1 1 D)* repmat(置换(B,[1 3 2]),[1,M 1])。

I have 2 matrices A (nxm) and B (nxd) and want to multiply element-wise each column of A with a row of B. There are m columns in A and n 1xd vectors in B so the results are m nxd matrices. Then I want to sum(result_i, 1) to get m 1xd vectors, which I want to apply vertcat to get a mxd matrix. I'm doing this operations using for loop and it is slow because n and d are big. How can I vectorize this in matlab to make it faster? Thank you.

EDIT:
You're all right: I was confused by my own question. What I meant by "multiply element-wise each column of A with a row of B" is to multiply n elements of a column in A with the corresponding n rows of B. What I want to do with one column of A is as followed (and I repeat this for m columns of A, then vertcat the C's vector together to get an mxd matrix):

column_of_A =

     3
     3
     1


B =

     3     1     3     3
     2     2     1     2
     1     3     3     3


C = sum(diag(column_of_A)*B, 1)

     16    12    15    18

解决方案

You can vectorize your operation the following way. Note, however, that vectorizing comes at the cost of higher memory usage, so the solution may end up not working for you.

%# multiply nxm A with nx1xd B to create a nxmxd array
tmp = bsxfun(@times,A,permute(B,[1 3 2]));

%# sum and turn into mxd
out = squeeze(sum(tmp,1));

You may want to do everything in one line, which may help the Matlab JIT compiler to save on memory.

EDIT

Here's a way to replace the first line if you don't have bsxfun

[n,m] = size(A);
[n,d] = size(B);
tmp = repmat(A,[1 1 d]) .* repmat(permute(B,[1 3 2]),[1,m,1]);

这篇关于如何在矢量化MATLAB这个矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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