MATLAB: Distance between two point with the same value

distanceMATLAB and Simulink Student Suite

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

Best Answer

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