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

coordinatedistanceStatistics and Machine Learning Toolbox

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!

Best 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)
Related Question