如何根据 Matlab kmean() 函数的输出计算与簇质心的距离

How to calculate distance from cluster centroids from the outputs of Matlab kmean() function

我有 2 个来自 k 均值 matlab 函数的输出簇
[idx,C] = kmeans(X,2);

我不知道如何使用"idx"

计算质心与簇中每个点之间的距离

我想得到所有点到质心的距离 >2

的矩阵
% not Matlab code; just illustrating concept    

例子 c1->{x1,x2}= x1-c1=3 x2-c1=2

c2->{y1,y2}=
y1-c2=4
y2-c2=1

output={y1,x1}

这样试试:

更新答案现在使用循环。

r = randn(300,2)*5;
r(151:end,:) = r(151:end,:) + 15;

n_clusters = 2;

[idx, C] = kmeans(r, n_clusters);

clusters = cell(n_clusters, 1);
distances = cell(n_clusters, 1);
for ii = 1:n_clusters
    clusters{ii} = r(idx==ii, :);
    distances{ii} = sqrt(sum((clusters{ii}-C(ii,:)).^2,2));    
end

figure;
subplot(1,2,1);   
for ii = 1:n_clusters
    plot(clusters{ii}(:,1), clusters{ii}(:,2), '.');
    hold on
    plot(C(ii,1), C(ii,2), 'ko','MarkerFaceColor', 'w');
end

title('Clusters and centroids');

subplot(1,2,2);

for ii = 1:n_clusters
    plot(clusters{ii}(distances{ii} > 2,1), clusters{ii}(distances{ii} > 2,2), '.');
    hold on
    plot(C(ii,1), C(ii,2), 'ko','MarkerFaceColor', 'w');
end
title('Centroids and points with distance > 2');

要得到一个点数大于 2 的矩阵的单元格,你可以这样做:

distant_points = cell(n_clusters,1);
for ii = 1:n_clusters
    distant_points{ii} = clusters{ii}(distances{ii} > 2,:)
end