Calculate the distance between points in 2-D space and output a distance matrix

Hello all, I am very new to Matlab and I am having quite a bit of difficulty understanding how to calculate the distance between pairs of points in a 2-D space. I need to develop a function to create an array of points and find the distances between every pair of points. The output of the function will be a distance matrix. The inputs to the function will be xstart, ystart, xend, yend, Nx, Ny. The total number of points will be Npts = Nx*Ny. The output will be a square matrix of size (Npts,Npts). Element (i,j) of this matrix will have the distance between point i and point j. The points will be numbered first along the x direction and then along the y, shown in the figure. For example, suppose the inputs are xstart = 1, ystart = 1, xend = 4, yend = 5, Nx = 3, and Ny = 3. So far, I have created some basic variables and I have the coordinate ranges for these values to be:
Npts = Nx*Ny;
dist = zeros(Npts); %creates empty output matrix to be updated
xrange = linspace(xstart,xend,Nx);
yrange = linspace(ystart,yend,Ny);
The 2-D space with these input variables should produce points with the following coordinates:
The solution for this example should look like:
It should be as simple as using two nested for loops but I can't get anything to make sense of it. I am most confused as how to compile each coordinate set so that each point is assigned a space in 2-D. Any help or advice that could be provided would help a lot!

 Accepted Answer

Use meshgrid() and pdist2(). pdist2() is in the Statistics and Machine Learning Toolbox.
xstart = 1;
ystart = 1;
xend = 4;
yend = 5;
Nx = 3
Ny = 3
Npts = Nx*Ny;
dist = zeros(Npts); %creates empty output matrix to be updated
xrange = linspace(xstart,xend,Nx);
yrange = linspace(ystart,yend,Ny);
[x, y] = meshgrid(xrange, yrange);
pts = [x(:), y(:)]
distances = pdist2(pts, pts)

3 Comments

I have a similar question but the input is a set of any number of points
(example:)
points= {[1,1],[2,2],[4,4]}
and I want to find the distance between each one and have the solution kinda come out like above, in that matrix form
Get them out of a cell array into a regular numerical array of size 3x2 where the first column is x and the second column is y. Then
pts = [x(:), y(:)]
distances = pdist2(pts, pts)
should work.
thank you! yes! wow mine was getting really complicated

Sign in to comment.

Asked:

on 17 Jan 2018

Commented:

on 1 Apr 2022

Community Treasure Hunt

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

Start Hunting!