MATLAB:在两个矩阵上应用函数的有效(矢量化)方法? [英] MATLAB: Efficient (vectorized) way to apply function on two matrices?

查看:114
本文介绍了MATLAB:在两个矩阵上应用函数的有效(矢量化)方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵X and Y,都为mxn阶.我想创建一个顺序为mxm的新矩阵O,以便通过分别将函数应用于XYithjth行来计算此新矩阵中的每个i,j th条目.就我而言,m = 10000n = 500.我尝试使用循环,但这需要永远.有有效的方法吗?

I have two matrices X and Y, both of order mxn. I want to create a new matrix O of order mxm such that each i,j th entry in this new matrix is computed by applying a function to ith and jth row of X and Y respectively. In my case m = 10000 and n = 500. I tried using a loop but it takes forever. Is there an efficient way to do it?

我的目标是两个功能点积-dot(row_i, row_j)exp(-1*norm(row_i-row_j)).但是我想知道是否有一种通用方法可以插入任何功能.

I am targeting two functions dot product -- dot(row_i, row_j) and exp(-1*norm(row_i-row_j)). But I was wondering if there is a general way so that I can plugin any function.

推荐答案

解决方案1 ​​

对于第一种情况,您似乎可以在转置Y-

For the first case, it looks like you can simply use matrix multiplication after transposing Y -

X*Y'

如果您要处理复数-

conj(X*ctranspose(Y))

解决方案2

对于第二种情况,您需要做更多的工作.您需要将bsxfunpermute一起使用以重新排列尺寸,并采用norm计算的原始形式,最后使用squeeze以获得二维数组输出-

For the second case, you need to do a little more work. You need to use bsxfun with permute to re-arrange dimensions and employ the raw form of norm calculations and finally squeeze to get a 2D array output -

squeeze(exp(-1*sqrt(sum(bsxfun(@minus,X,permute(Y,[3 2 1])).^2,2)))

如果您想避免使用squeeze,则可以使用两个permute的-

If you would like to avoid squeeze, you can use two permute's -

exp(-1*sqrt(sum(bsxfun(@minus,permute(X,[1 3 2]),permute(Y,[3 1 2])).^2,3)))

我也建议您研究此问题-在Matlab中高效地计算成对平方的欧几里得距离.

I would also advise you to look into this problem - Efficiently compute pairwise squared Euclidean distance in Matlab.

总而言之,对于X的ithjth行,没有一种通用的最有效的方法可以用于每个函数.如果您仍然对此不满意,可以使用带有bsxfun的匿名函数句柄,但恐怕不会是最有效的技术.

In conclusion, there isn't a common most efficient way that could be employed for every function to ith and jth row of X. If you are still hell bent on that, you can use anonymous function handles with bsxfun, but I am afraid it won't be the most efficient technique.

这篇关于MATLAB:在两个矩阵上应用函数的有效(矢量化)方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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