Distance between two point with the same value

1 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2019-11-18
编辑:Guillaume 2019-11-18
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by