-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_regions.m
124 lines (99 loc) · 2.6 KB
/
create_regions.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
function [table, cas] = create_regions(A, B, V, N, show)
% N = number of regions
% V = Value Map
% A = vector1
% B = vector2
% Table of the regions based on A and B
% cas = centroids of the regions
if (nargin < 5) || isempty(show)
show = 0;
end
maxIterations = 2500;
A = A(:).';
B = B(:).';
Y = (ones(length(A),length(B)).*B);
X = (ones(length(B),length(A)).*A)';
[finalCentroids, finalAssignments] = kMeans([X(:),Y(:),V(:)], N, maxIterations);
%%
%cdata = reshape(finalAssignments(:), [length(V),length(T)])
finas = finalAssignments(:);
idx = 1;
i=1;
addext = 0;
cas = finalCentroids;
if finas(i)>1
store = finas(i);
addext = addext+1;
cas = [cas; cas(idx,:)];
for j=1:length(finas)
if finas(j)==1
finas(j)=N+addext;
end
end
for j=i:length(finas)
if finas(j)==store
finas(j)=1;
end
end
cas(idx,:) = cas(store,:);
end
for i=2:length(finas)
if finas(i)>idx
if finas(i)==idx+1
idx = finas(i);
else
store = finas(i);
addext = addext+1;
idx = idx+1;
cas = [cas; cas(idx,:)];
for j=1:length(finas)
if finas(j)==idx
finas(j)=N+addext;
end
end
for j=i:length(finas)
if finas(j)==store
finas(j)=idx;
end
end
cas(idx,:) = cas(store,:);
end
end
end
table = reshape(finas(:), [length(A),length(B)]);
cas = cas(1:N,:);
if show
figure();
% Assign color based on the assignments
colormap(parula(max(finalAssignments(:))));
% Set the CData property to color the surface based on assignments
set(gca, 'CLim', [min(finas(:)), max(finas(:))]); % Adjust color limits
set(surf(X,Y,V), 'CData', table, 'FaceColor', 'interp');
% Add colorbar for reference
colorbar;
% Display final centroids and assignments
disp('Final Centroids:');
disp(finalCentroids);
%disp('Final Assignments:');
%disp(finalAssignments);
end
end
%%
function [centroids, assignments] = kMeans(points, k, maxIterations)
numPoints = size(points, 1);
numDimensions = size(points, 2);
% Initialize centroids randomly from the data points
centroids = points(randperm(numPoints, k), :);
for iter = 1:maxIterations
% Assign each point to the nearest centroid
distances = pdist2(points(:,numDimensions), centroids(:,numDimensions));
[~, assignments] = min(distances, [], 2);
% Update centroids
for i = 1:k
clusterPoints = points(assignments == i, :);
if ~isempty(clusterPoints)
centroids(i, :) = mean(clusterPoints);
end
end
end
end