matlab 维诺图质心算法

matlab 维诺图质心算法。

function [centroids, clusters] = voronoi_centroid(points)
%VORONOI_CENTROID Vornoi diagram centroid-based clustering algorithm
%
% [CENTROIDS, CLUSTERS] = VORONOI_CENTROID(POINTS) computes the centroids
% and cluster assignments of a set of n-dimensional points using the
% Voronoi diagram and the centroids of its regions.
%
% Arguments:
% POINTS: A matrix of n-dimensional points, one point per row.
%
% Returns:
% CENTROIDS: A matrix with one centroid per row, corresponding to the
% points in the order they appear in CLUSTERS.
% CLUSTERS: A vector with one entry per point, indicating the index
% into the CENTROIDS matrix of the centroid to which that point
% belongs.

% Compute the Voronoi diagram.
[~, E] = voronoin(points);

% Initialize the centroids and the clusters.
centroids = zeros(size(points));
clusters = zeros(length(points), 1);

% Loop over all edges in the Voronoi diagram.
for i = 1:length(E)
% Indices of the points defining this edge.
idx = E{i};

% If this is an infinite edge, ignore it.
if any(idx == 1), continue; end

% Compute the centroid of the region defined by this edge.
x = mean(points(idx, :));

% Update the closest cluster index for each point in this region.
for j = idx’
d = norm(points(j, 🙂 – x);
if d < norm(points(j, :) - centroids(clusters(j), :))
clusters(j) = i;
end
end

% Update the centroid for this cluster.
centroids(i, 🙂 = x;
end
% Remove any unused centroids.
centroids = centroids(any(clusters == (1:length(E))’, 1), :);
end

相关文章