k-medians clustering technique

7 ビュー (過去 30 日間)
muhammad ismat
muhammad ismat 2017 年 3 月 13 日
コメント済み: Federico Maddanu 2025 年 3 月 14 日
please, i want matlab code of k-median clustering technique

回答 (1 件)

NVSL
NVSL 2025 年 1 月 24 日
I recently looked into whether there's a function for k-median clustering in MATLAB, or if we could tweak the existing "k-means" or "k-medoids" functions to do the job.
I couldn't find anything ready-made, but I figured out that we can use MATLAB's "median" function to create our own "kMedianClustering" function. Hope this helps!
function [centroids, idx] = kMedianClustering(X, k, maxIter)
% X: data points (n x d matrix)
% k: number of clusters
% maxIter: maximum number of iterations
% Initialize centroids randomly
[n, d] = size(X);
centroids = X(randperm(n, k), :);
idx = zeros(n, 1);
for iter = 1:maxIter
% Assign each point to the nearest centroid
for i = 1:n
distances = sum(abs(X(i, :) - centroids), 2);
[~, idx(i)] = min(distances);
end
% Update centroids
newCentroids = zeros(k, d);
for j = 1:k
clusterPoints = X(idx == j, :);
if ~isempty(clusterPoints)
newCentroids(j, :) = median(clusterPoints, 1);
else
newCentroids(j, :) = centroids(j, :);
end
end
% Check for convergence
if all(newCentroids == centroids)
break;
end
centroids = newCentroids;
end
end
% randomly generated data
data = [randn(50, 2) + 1; randn(50, 2) - 1];
% Number of clusters
k = 2;
% Maximum number of iterations
maxIter = 100;
% Perform k-median clustering
[centroids, idx] = kMedianClustering(data, k, maxIter);
% Plot the results
figure;
hold on;
colors = ['r', 'g', 'b'];
for i = 1:k
scatter(data(idx == i, 1), data(idx == i, 2), 36, colors(i), 'filled');
end
scatter(centroids(:, 1), centroids(:, 2), 100, 'kx', 'LineWidth', 3);
hold off;
title('K-Median Clustering');
  1 件のコメント
Federico Maddanu
Federico Maddanu 2025 年 3 月 14 日
I think (but I m not sure) kmeans does this when you select 'cityblock' as distance!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCluster Analysis and Anomaly Detection についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by