clc;
fprintf('Beginning to run %s.m.\n', mfilename);
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 22;
numPoints = 200;
pointsPerCluster = 5;
numClusters = ceil(numPoints / pointsPerCluster)
coordinates = zeros(pointsPerCluster, 2, numClusters);
t = table(zeros(numPoints, 1), zeros(numPoints, 1), zeros(numPoints, 1), zeros(numPoints, 1), 'VariableNames', {'ClusterNumber', 'PointNumber', 'x', 'y'});
xy = rand(numPoints, 2);
x = xy(:, 1);
y = xy(:, 2);
subplot(1, 2, 1);
plot(x, y, 'b.', 'MarkerSize', 14);
grid on;
distances = pdist2(xy, xy);
minDistance = min(distances(distances~=0))
[row, col] = find(distances == minDistance)
currentRow = row(1)
pointer = 1;
for k = 1 : numClusters
distances = pdist2(xy, xy(currentRow, :));
minDistances = mink(distances, pointsPerCluster);
[ia, ib] = ismember(distances, minDistances);
rows = find(ib);
for n = 1 : length(rows)
t.ClusterNumber(pointer) = k;
t.PointNumber(pointer) = n;
t.x(pointer) = xy(rows(n), 1);
t.y(pointer) = xy(rows(n), 2);
pointer = pointer + 1;
end
if pointer >= numPoints
break;
end
xy(rows, :) = inf;
distances = pdist2(xy, xy);
minDistance = min(distances(distances~=0));
[row, col] = find(distances == minDistance);
currentRow = row(1);
end
subplot(1, 2, 2);
gscatter(t.x, t.y, t.ClusterNumber);
Best Answer