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

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

    To start with, you are computing twice as much as you need to here, because D will be symmetric. You don't need to calculate the (i,j) entry and the (j,i) entry separately. Change your inner loop to for j=1:i, and add in the body of that loop D(j,i)=D(i,j);

    After that, there's really not much redundancy left in what that code does, so your only room left for improvement is to parallelize it: if you have the Parallel Computing Toolbox, convert your outer loop to a parfor and before you run it, say matlabpool(n), where n is the number of threads to use.

提交回复
热议问题