Distance Matrix Without Loop

3 views (last 30 days)
Sofia Blyufer
Sofia Blyufer on 14 Nov 2020
Edited: Matt J on 14 Nov 2020
Hi all,
I would like to get a matrix A that for each aij, I'd get the distance (i.e. abs(x-y)) between the i and j values in the following manner:
x = [3, 5, 10];
y = [3, 5, 10]; % those are the locations in x and y, they are the same
Desired Matrix:
A = [0 2 7
2 0 5
7 5 0];
Please notice it's normal abs(x-y) and not the euclidean distance as technically both x and y are on the same axis.
I do know I can do a for loop to achieve this, but I might have a very large matrix and I was wondering if a quicker way is possible.
Thanks!

Answers (1)

Matt J
Matt J on 14 Nov 2020
Edited: Matt J on 14 Nov 2020
x = [3, 5, 10];
y = [3, 5, 10];
A = abs(x(:)-y(:).')
A = 3×3
0 2 7 2 0 5 7 5 0

Community Treasure Hunt

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

Start Hunting!