k-medians clustering technique

11 visualizzazioni (ultimi 30 giorni)
muhammad ismat
muhammad ismat il 13 Mar 2017
Commentato: Federico Maddanu il 14 Mar 2025
please, i want matlab code of k-median clustering technique

Risposte (1)

NVSL
NVSL il 24 Gen 2025
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 Commento
Federico Maddanu
Federico Maddanu il 14 Mar 2025
I think (but I m not sure) kmeans does this when you select 'cityblock' as distance!

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by