# Calculating the distance between points using vectorization.

139 views (last 30 days)
Giuseppe on 23 Mar 2014
Commented: Giuseppe on 24 Mar 2014
Hi I have the matrix;
points = [2 5; 6 9; 7 8; 9 10; 6 10]
These points relate to a set of x and y coordinates. I want to calculate the distance between each of the points e.g. distance between 2 5 and 6 9 and 6 9 and 7 8 and so on until 6 10 is last point and the distance between it and 2 5. These points create an area such that I want to calculate the perimeter.
I know the distance formula is;
distance_between_two_points = sqrt((x2-x1)^2 + (y2-y1)^2)
So that the distance between 2 5 and 6 9 would be;
distance_between_two_points = sqrt((6-2)^2 + (9-5)^2)
How would I use vectorization to calculate the distance between all of the points. I also then need to calculate perimeter but I have figured I will use the sum function. Also how could I make it such that if the values for the points changed I would get the answer and so that if extra points were added this would be accounted for.
Thanks.
NOTE: No built in functions for perimeter or distance are to be used.

Jan on 23 Mar 2014
points = [2 5; 6 9; 7 8; 9 10; 6 10];
Diff = [diff(points, 1); points(end, :)-points(1, :)];
Dist = sqrt(sum(Diff .* Diff, 2));
Giuseppe on 24 Mar 2014
I like the simplicity of this. Thanks.

Azzi Abdelmalek on 23 Mar 2014
points = [2 5; 6 9; 7 8; 9 10; 6 10]
for k=1:size(points,1)-1
p1=points(k,:);
p2=points(k+1:end,:);
a=bsxfun(@minus,p2,p1)
d{k,1}=sqrt(sum(a.^2,2))
end
out=cell2mat(d)

Mischa Kim on 23 Mar 2014
Giuseppe, would this do?
points = [2 5; 6 9; 7 8; 9 10; 6 10];
b = points - circshift(points,-1,1);
len = sqrt(sum(b.*b,2))

### Categories

Find more on Operating on Diagonal Matrices 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!

Translated by
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}