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

前端 未结 4 1930
不思量自难忘°
不思量自难忘° 2021-02-11 02:02

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:39

    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.

提交回复
热议问题