Distance between two point with the same value

2 views (last 30 days)
Hi,
I have a matrix like the one below and i need to get the mean distance between each 3, each 2 etc...
I tried to use several diastance function (like pdist etc) but none of these give an exploitable result (or maybe i misunderstood how its work).
Thank you for your help.
n=randi(3,10)
n =
1 2 3 2 1 1 2 1 3 1
2 1 3 2 1 3 1 1 2 3
3 3 2 3 2 2 2 3 2 3
1 1 2 2 1 1 3 1 1 3
1 3 2 2 3 3 1 3 2 1
1 1 1 3 1 3 1 3 2 1
2 2 2 3 1 2 1 2 3 2
3 2 2 2 1 1 1 2 2 3
2 3 3 2 1 1 2 1 2 1
2 1 3 2 2 2 2 2 3 1

Accepted Answer

Guillaume
Guillaume on 18 Nov 2019
Edited: Guillaume on 18 Nov 2019
Assuming euclidean distance metric:
n = randi(3, 10); %demo input
vals = unique(n); %get unique values in n
mdistances = zeros(size(vals)); %create storage for mean of distance for each unique value
for vidx = 1:numel(vals) %iterate over each unique value
[rows, cols] = find(n == vals(vidx)); %get location of all points with that unique value
dist = hypot(rows - rows.', cols - cols.'); %calculate distance between each pair of point. Creates a symmetric matrix
mdistances = mean(dist(tril(true(size(dist)), -1))); %calculate mean of lower triangular matrix below diagonal of dist. i.e. distance between each unique pair of points
end
edit: spelling

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!