Warm tip: This article is reproduced from stackoverflow.com, please click
matlab euclidean-distance

matlab

发布于 2020-04-10 16:12:43

I have a number of objects that each have three matrices of distance between own points (x1-x1,x1-x2,x1-x3...;x2-x1,x2-x2,x3-x2...) also with y and z.

I want to find as many nearby points as possible, assuming rotation is not an issue.

I tried something. Since Matlab is supposed to work easy with matrices I am sure something is cumbersome but I don't know how to fix it. For each object and it's mirror, and for each translation on each axes there is an xyz scenario: (x1,y1,z1;x2,y2,z2;...) So I am translating and mirroring one object a million times.

for m=1:object1
for n=1:object2
 for i=1:NumRows
 for j=1:NumRows2
  d_x(m,n,i,j)=obj(m).xyz(i,1)-obj(n).xyz(j,1);
  d_y(m,n,i,j)=obj(m).xyz(i,2)-obj(n).xyz(j,2);
  d_z(m,n,i,j)=obj(m).xyz(i,3)-obj(n).xyz(j,3);
  d_r(m,n,i,j)=sqrt(d_x(m,n,i,j)*d_x(m,n,i,j)+d_y(m,n,i,j)*d_y(m,n,i,j)+d_z(m,n,i,j)*d_z(m,n,i,j));
  if d_r(m,n,i,j)>=0 & d_r(m,n,i,j)<1.2
   d_r(m,n,i,j)=1.2-d_r(m,n,i,j);
  else
   d_r(m,n,i,j)=0;
  end
  sy(m,n)=sy(m,n)+d_r(m,n,i,j);
 end
 end
end
end
Questioner
Joita Dan
Viewed
54
Daniel 2020-02-02 23:02

Whenever you start putting indices in variable names, think twice if they maybe should be a single variable. Here we have d_x d_y d_z. My recommendation would be to replace them by a single variable:

d_xyz(m,n,i,j,:)=obj(m).xyz(i,:)-obj(n).xyz(j,:);

And now to your next line, what you are calculating there is actually called a 2-norm. If you know the name, it's simple to shorten:

d_r(m,n,i,j) = norm(squeeze(d_xyz(m,n,i,j,:)),2);