Calculate the distance between points in a large data set
Show older comments
I have a number of x and y coordinates.
I want to find the distance (sqrt(x^2+y^2)) from a point to the point in behind it, like in the image below.

What would be the best way to do this without using this code forever.
Distance_x_1 = (x(2,1) - x(1,1))^2
Distance_y_1 = (y(2,1) - y(1,1))^2
Distnace_1 = sqrt(Distance_x_1+Distance_y_1)
Distance_x_2 = (x(3,1) - x(2,1))^2
Distance_y_2 = (y(3,1) - y(2,1))^2
Distnace_2 = sqrt(Distance_x_1+Distance_y_1)
Accepted Answer
More Answers (2)
Jan
on 26 Apr 2022
Do not create a pile of variables but a vector, which contains the distances:
Distance = sqrt(diff(x).^2 + diff(y).^2);
John showed you one approach. Two others that come to mind are to use the hypot or vecnorm functions.
% Sample data
xy = rand(10,2);
johnApproach = sqrt(sum(diff(xy).^2,2));
% Take the 2-norm (the first 2 below) along dimension 2
vecnormApproach = vecnorm(diff(xy, 1), 2, 2);
d = diff(xy, 1);
hypotApproach = hypot(d(:, 1), d(:, 2));
% Show the results
format longg
results = table(johnApproach, vecnormApproach, hypotApproach)
Those results seem to match to me.
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!