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

前端 未结 4 902
小蘑菇
小蘑菇 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:47

    I think this is what you're looking for.

    D=zeros(N);    
    jIndx=repmat(1:N,N,1);iIndx=jIndx'; %'# fix SO's syntax highlighting
    D(:)=sqrt(sum((x(iIndx(:),:)-x(jIndx(:),:)).^2,2));
    

    Here, I have assumed that the distance vector, x is initalized as an NxM array, where M is the number of dimensions of the system and N is the number of points. So if your ordering is different, you'll have to make changes accordingly.

提交回复
热议问题