Find K-Means average distance from points within a cluster to their respective centroid?
40 views (last 30 days)
Show older comments
I've run the k-means algorithm on my data and it returns "D" = distances from each point in the data set to every centroid, and "sumd" = within-cluster sums of point-to-centroid distances. However, I would like to find a way to calculate the mean distance from points within a cluster to their centroids. What is the best way to do this?
0 Comments
Accepted Answer
Image Analyst
on 16 Dec 2021
The second argument of kmeans is the cluster centroids. It's an easy matter to get the distance from each point in a class to the centroid. Let's say you have 3 classes and data has two coordinates, x, and y.
numClasses = 3;
[classIndexes, clusterCentroids] = kmeans(data, numClasses);
meanDistances = zeros(numClasses, 1);
for k = 1 : numClasses
% Get x and y of centroid.
xc = clusterCentroids(k, 1);
yc = clusterCentroids(k, 2);
% Get the x and y coordinates of points within this class only.
inClass = classIndexes == k; % Indexes of points that were assigned to this class.
x = data(inClass, 1); % Get not ALL x, but just x within this one class.
y = data(inClass, 2); % Get not ALL y, but just y within this one class.
% Get distances of all points in the class to the centroid for this class.
distances = sqrt((x - xc) .^ 2 + (y - yc) .^ 2);
meanDistances(k) = mean(distances);
end
The concept can be generalized to any number of features. Instead of 2 you can have 3 or 4 or 20. It doesn't matter - just make the obvious changes to generalize it. How many features do you have?
10 Comments
Image Analyst
on 28 Dec 2021
I've worked on MRI images before but not specifically fMRI that I remember.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!