优化MATLAB代码(嵌套for循环计算相似度矩阵)

arm*_*dle 2 optimization matlab

我在MATLAB中基于欧几里德距离计算相似度矩阵.我的代码如下:

for i=1:N % M,N is the size of the matrix x for whose elements I am computing similarity matrix
 for j=1:N
  D(i,j) = sqrt(sum(x(:,i)-x(:,j)).^2)); % D is the similarity matrix
 end
end
Run Code Online (Sandbox Code Playgroud)

可以帮助优化这个=减少for循环,因为我的矩阵x具有维度256x30000.

非常感谢!

--Aditya

twe*_*ter 5

在matlab中执行此操作的函数称为pdist.不幸的是,它很慢,并没有考虑到Matlabs矢量化能力.

以下是我为项目编写的代码.让我知道你得到什么样的速度.

   Qx=repmat(dot(x,x,2),1,size(x,1));
   D=sqrt(Qx+Qx'-2*x*x');
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于您的数据点位于行中且尺寸为列的情况.例如,假设我使用x = rand(256,100000)在我的mac上有256个数据点和100000个维度,上面的代码在大约半秒内产生256x256矩阵.