MATLAB: Efficient (vectorized) way to apply function on two matrices?

 ̄綄美尐妖づ 提交于 2019-12-24 02:32:54

问题


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?

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:


Solution #1

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

X*Y'

If you are dealing with complex numbers -

conj(X*ctranspose(Y))

Solution #2

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)))

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)))

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


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.




回答2:


For the second part, you could also use pdist2:

result = exp(-pdist2(X,Y));


来源:https://stackoverflow.com/questions/26192800/matlab-efficient-vectorized-way-to-apply-function-on-two-matrices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!