Optimize MATLAB code (nested for loop to compute similarity matrix)

前端 未结 4 909
小蘑菇
小蘑菇 2021-02-11 01:54

I am computing a similarity matrix based on Euclidean distance in MATLAB. My code is as follows:

for i=1:N % M,N is the size of the matrix x for whose elements I         


        
4条回答
  •  广开言路
    2021-02-11 02:41

    The function to do so in matlab is called pdist. Unfortunately it is painfully slow and doesnt take Matlabs vectorization abilities into account.

    The following is code I wrote for a project. Let me know what kind of speed up you get.

       Qx=repmat(dot(x,x,2),1,size(x,1));
       D=sqrt(Qx+Qx'-2*x*x');
    

    Note though that this will only work if your data points are in the rows and your dimensions the columns. So for example lets say I have 256 data points and 100000 dimensions then on my mac using x=rand(256,100000) and the above code produces a 256x256 matrix in about half a second.

提交回复
热议问题