how to calculate distance between one and other points?

I have 6 sets of data (x,y,z,grid_x,grid_y,grid_z), xyz have 100 points and it is detemine by me randomly, grid_xyz is the detemining the grid, from(0,0) to (100,100) with 2m intervals, which means grid_x = (0,2,4,6,..), grid_y= (0,2,4,6,..), I need to calculate the distance between (x,y) to (grid_x,grid_y), that is calculate each (grid_x,grid_y) to all the point (x,y), for instance (0,0) to (x1,y1) (x2,y2) (x3,y3)...(x100,y100), then (0,2) to (x1,y1) (x2,y2) (x3,y3)...(x100,y100) and so on. how to calculate this? thank you so much!

 Accepted Answer

You can use pdist2()
xyz1 = [x(:), y(:), z(:)];
xyz2 = [grid_x(:), grid_y(:), grid_z(:)];
distances = pdist2(xyz1, xyz2);
Now you have the distance of every point in xyz to every point in xyz2. If you want to find the closest point to xyz that is in xyz2, you can examine the rows for the min distance.

3 Comments

Thank you so much!! but I only need to calculate the 2D distance between them first, so I changed it to
xyz1 = [x(:), y(:)];
xyz2 = [grid_x(:), grid_y(:)];
distances = pdist2(xyz1, xyz2);
but the distances haven't came up. How can I fix this? (xyz1 is 100x2, xyz2 is 51x2)
What do you mean haven't come up? Take the semicolon off and it should spit out a 100 row by 51 column matrix to the command window. Or else look at it in the variable editor (Double click on distances in the workspace panel).
Thank you!! I give you my code below. It only generated table xy1,xy2 but don't have the distance(d) table.
clear all
## import data
pkg load io
data = xlsread(' data.xlsx');
## categorize the data
x = data(:,1);
y = data(:,2);
z = data(:,3);
## 2nd order polynomial interpolation
## Find polynomial coefficient
A = [ones(size(data,1),1) x y x.*y x.^2 y.^2];
a = pinv(A)*z;
## interpolation
grid_x = [0:2:100]';
grid_y = grid_x;
grid_z = zeros(size(grid_x,1), size(grid_x,1));
for i1 = 1:size(grid_x,1)
for i2 = 1:size(grid_y, 1)
A = [1 grid_x(i1) grid_y(i2) grid_x(i1).*grid_y(i2) grid_x(i1).^2 grid_y(i2).^2];
grid_z(i1, i2) = A*a;
end
end
##distance
xy1 = [x(:), y(:)];
xy2 = [grid_x(:), grid_y(:)];
d = pdist2(xy1, xy2);

Sign in to comment.

More Answers (0)

Categories

Asked:

on 25 Feb 2022

Commented:

on 25 Feb 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!