MATLAB Answers


K-Means: Indices of C in idx

Asked by Maurizio Cimino on 17 Jul 2019
Latest activity Edited by Maurizio Cimino on 17 Jul 2019
Hello, I'm using the built-in kmeans function but I don't understand a thing. After I've applied the function, I have two output parameters: idx and C. The first one is a matrix containing, for each observation, the cluster's index where it has been classified. The second one is the matrix containing all the centroids location. Well, is there a way to know which are the indices of the centroids C inside the matrix idx? For example, I would like to know the index inside idx of C(:,1), etc.
Thank you very much.


Sign in to comment.

1 Answer

Answer by the cyclist
on 17 Jul 2019
 Accepted Answer

I'm not certain I fully understand your question, but I'll make a guess.
The centroid is not (necessarily) one of the points of the original dataset, so none of the rows of idx correspond to the centroid itself.
The centroid locations are given by the rows of C (not the columns). The row C(1,:) is the centroid for the cluster of points with idx=1. The row C(2,:) is the centroid for the cluster of points with idx=2. And so on.
If that doesn't answer your question, maybe you could comment with some clarification.


Thank you for your reply.
I've applied the kmeans function and I have the C matrix. Because the elements are images, I've tried to display all the centroids in C and it seems that every centroid is a point of my dataset. I tried different times and it's always like that. Now, because of that, I would like to know which is the position of this image (centroid) in the array idx.
the cyclist
on 17 Jul 2019
Here is a trivial example where the centroids are not in the dataset:
x = [-2 -1 1 2]';
y = [0 0 0 0]';
[idx,C] = kmeans([x y],2);
hold on
% Plot data points
% Plot centroids
h(1) = plot(C(1,1),C(1,2),'.');
h(2) = plot(C(2,1),C(2,2),'.');
I am certain that MATLAB is not going to output which data point (from the original data) is the centroid, because it is not guaranteed to be in the dataset.
You could call with the syntax
[idx,C,sumd,D] = kmeans()
and find the point with the minimum within-cluster distance.
Thank you for your reply.
Okay, very good idea. I have done like this: I just use D to compute, for each column, which is the minimum element (the nearest data-point from the current centroid).
Thank you very much.

Sign in to comment.