Distance between two point with the same value
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
1 commentaire
Réponse acceptée
Guillaume
le 18 Nov 2019
Modifié(e) : Guillaume
le 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!