clear all
clc
% randomly construct the samples
x_1 = [-2:0.05:2];
y_1 = sqrt((4 - x_1 .^ 2) .+ 4*rand(size(x_1)));
x_2 = [-4:0.05:4];
y_2 = sqrt((16 - x_2 .^ 2) .+ 8*rand(size(x_2)));
x = [x_1, x_2];
y = [y_1, y_2];
trainData = [x', y'];
figure();
subplot(1, 1, 1);
hold on;
% drow all the points
scatter(trainData(:, 1), trainData(:, 2), 'g', 'linewidth', 3);
xlim([-5,5]);
ylim([0,6]);
%axis equal;
grid on;
xlabel('x1');
ylabel('x2');
% now we get the data.
% begin to run the SBSCAN.
m = size(trainData)(1);
% set tag of each sample, -1: no tag, 0: alone point, 1: edge point, and another points are tagged point.
tag = -ones(m, 1);
% this array is only to edge point, it represents its belongs
edge_ponit_TypeTag = zeros(m, 1);
NormalType = 2;
% set the circle area, banjing
% set the threshold
R = 0.5;
Minpts = 3;
alone_p = 0;
edge_p = 1;
for i=1:m
if tag(i) != -1
continue;
end;
% calculate the distance of each sample to another all sample.
dis = sqrt(((trainData(i, :) .- trainData) .^ 2) * ones(2,1));
% find the points which are in this circle area.
neghbours = find(dis <= R);
if size(neghbours)(1) == 1
tag(i) = alone_p; % alone point
continue;
elseif size(neghbours)(1) < (Minpts+1)
tag(i) = edge_p; % edge point
continue;
end;
% create a new type of cluster
tag(i) = NormalType; % core point
% init the 动态数组.
array = neghbours;
NormalType
% deep iteration to find all the core points.
while !isempty(array)
% pop the first
point = array(1);
array(1) = []; % pop(remove) this point
% ignore the core point itself.
if point == i
continue;
end;
if tag(point) == 1
edge_ponit_TypeTag(point) = NormalType; % record this edge point to core point's tag
continue;
elseif tag(point) != -1
continue; % ignore the alone point and tagged point
end;
% calculate the distance of each sample to another all sample.
dis = sqrt(((trainData(point, :) .- trainData) .^ 2) * ones(2,1));
% find the points which are in this circle area.
neghbours = find(dis <= R);
if size(neghbours)(1) == 1
tag(point) = alone_p; % alone point
continue;
elseif size(neghbours)(1) < (Minpts+1)
tag(point) = edge_p; % edge point
continue;
else
tag(point) = NormalType; % core point
end;
% append(insert) to the 动态数组.
array = [array; neghbours];
end;
% another type
NormalType++;
end;
% correct the NormalType
NormalType--;
% covert all the edge point to its belonging tag
idx = find(edge_ponit_TypeTag > 0);
tag(idx) = edge_ponit_TypeTag(idx);
% covert all the alone point to 1, color(1) = 'black'
idx = find(tag == alone_p);
tag(idx) = 1;
% set color to draw
color = ['k', 'r', 'g', 'b', 'c', 'm', 'y'];
% drow all the points
figure();
for i=1:NormalType
subplot(1, NormalType, i);
hold on;
% drow all the points
idx = find(tag == i);
data = trainData(idx, :);
scatter(data(:, 1), data(:, 2), color(i), 'linewidth', 3);
xlim([-5,5]);
ylim([0,6]);
%axis equal;
grid on;
xlabel('x1');
ylabel('x2');
end;