k-medians clustering technique

조회 수: 6 (최근 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 CenterFile 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!

Translated by