# Distance between two set of points in space

5 views (last 30 days)
andrea on 26 Jan 2022
Commented: David Hill on 27 Jan 2022
Hello,
So I have a set of points in a matrix A 10x3 ( i.e 10 points with x,y,z coordinates) and another set of points in a matrix B 10x3. I want to find the distance between each point of A with each point of B whitout using a for loop.
Normally I would fix a point in A and compute all the distances with the points in B and then choose another point in A and do the same and so on. Is there a way to do it directly from the matrix A and B whitout a loop ?

Matt J on 26 Jan 2022
distances = pdist2(A,B);

David Hill on 26 Jan 2022
Why no loop? Below is oneliner but has an internal loop.
C=arrayfun(@(x)vecnorm((A(x,:)-B)'),1:size(A,1),'UniformOutput',false);
##### 2 CommentsShow 1 older commentHide 1 older comment
David Hill on 27 Jan 2022
pdist2(A,B)

### Categories

Find more on Hierarchical Clustering in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!