Getting the nearest data index points to centriodes in Kmeans clustering in MATLAB

I am doing K-clustering in MATLAB. As you know, usage will be as follows:

[IDX,C] = kmeans(X,k)

where IDX gives the cluster number for each data point in X, and C gives centroids for each cluster. I need to get the index (row number in the actual dataset X) of the closest datapoint to the centroid. Does anyone know how I can do this? Thanks

+5
source share
4 answers

"Brute force approach," as @Dima mentioned , would look like this

%# loop through all clusters
for iCluster = 1:max(IDX)
    %# find the points that are part of the current cluster
    currentPointIdx = find(IDX==iCluster);
    %# find the index (among points in the cluster)
    %# of the point that has the smallest Euclidean distance from the centroid
    %# bsxfun subtracts coordinates, then you sum the squares of
    %# the distance vectors, then you take the minimum
    [~,minIdx] = min(sum(bsxfun(@minus,X(currentPointIdx,:),C(iCluster,:)).^2,2));
    %# store the index into X (among all the points)
    closestIdx(iCluster) = currentPointIdx(minIdx);
end

, k,

X(closestIdx(k),:)
+5

k-, . Matlab.

, k-medoids, "" . matlab.

+1

In fact, kmeans already gives you the answer, if I understand you correctly:

[IDX,C, ~, D] = kmeans(X,k); % D is the distance of each datapoint to each of  the clusters
[minD, indMinD] = min(D); % indMinD(i) is the index (in X) of closest point to the i-th centroid
0
source

How to change @Jonas code to get 10 closest points to centroid? Your help is appreciated

-1
source

All Articles