广义矩阵乘积 [英] Generalized Matrix Product

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

问题描述

我对MATLAB很陌生. M x K矩阵与K x N矩阵的标准矩阵乘法-C = A * B-具有c_ij = sum(a_ik * b_kj, k = 1:K).如果我希望对某些简单的二进制操作op取而代之的是c_ij = sum(op(a_ik, b_kj), k = 1:K)怎么办?有没有什么好的方法可以在MATLAB(甚至是内置函数)中对此向量化?

I'm fairly new to MATLAB. Normal matrix multiplication of a M x K matrix by an K x N matrix -- C = A * B -- has c_ij = sum(a_ik * b_kj, k = 1:K). What if I want this to be instead c_ij = sum(op(a_ik, b_kj), k = 1:K) for some simple binary operation op? Is there any nice way to vectorize this in MATLAB (or maybe even a built-in function)?

这是目前我能做的最好的事情.

This is currently the best I can do.

% A is M x K, B is K x N
% op is min
C = zeros(M, N);
for i = 1:M:
    C(i, :) = sum(bsxfun(@min, A(i, :)', B));
end

推荐答案

本文中列出的是一种矢量化方法,该方法始终存在 permute 来创建bsxfun所需的单例尺寸,以使singleton-expansion完成其工作,从而实质上替换了原始文章中的循环.请注意,bsxfun是一个内存消耗大的实现,因此,请期望仅在它拉伸得太远之前使用它进行加速.这是最终的解决方案代码-

Listed in this post is a vectorized approach that persists with bsxfun by using permute to create singleton dimensions as needed by bsxfun to let the singleton-expansion do its work and thus essentially replacing the loop in the original post. Please be reminded that bsxfun is a memory hungry implementation, so expect speedup with it only until it is stretched too far. Here's the final solution code -

op = @min;   %// Edit this with your own function/ operation
C = sum(bsxfun(op, permute(A,[1 3 2]),permute(B,[3 2 1])),3)

NB-上述解决方案的灵感来自在Matlab中删除四个嵌套循环.

NB - The above solution was inspired by Removing four nested loops in Matlab.

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

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