k-medians clustering technique
4 次查看(过去 30 天)
显示 更早的评论
please, i want matlab code of k-median clustering technique
0 个评论
回答(1 个)
NVSL
2025-1-24
Hello @muhammad ismat
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
2025-3-14
I think (but I m not sure) kmeans does this when you select 'cityblock' as distance!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cluster Analysis and Anomaly Detection 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!