K-Means Clustering Tutorial
Code for distance matrix computation is updated. Now it can handle multidimensional variables.
The previous code that work only for 2 dimensions is given here for historical purposes.
function d=dist(A,B)
% DIST return distance matrix between point A=[x1 y1] and B=[x2 y2]
% Number of points in A and B are not necessarily the same.
% It can be use for distance-in-a-slice, distance-between-slice,
% and distance between guest-points-and-the-points
% A and B must contain two columns,
% first column is the X coordinates
% second column is the Y coordinates
% The distance matrix are distance between points in A as row
% and points in B as column.
% example: distance-in-a-slice= dist(A,A)
% distance between guest-point-and-the-point = dist(A,B) , hA=hB
% distance between slices = dist(A,B), with hA ~= hB or hA=hB
% A=[1 2; 3 4; 5 6]; B=[4 5; 6 2; 1 5; 5 8]
% dist(A,B)= [ 4.24 5.00 3.00 7.21;
% 1.41 3.61 2.24 4.47;
% 1.41 4.12 4.12 2.00 ]
[hA,wA]=size(A)
[hB,wB]=size(B)
if hA==1& hB==1
d=sqrt(dot((A-B),(A-B)));
else
C=[ones(1,hB);zeros(1,hB)]
D=flipud(C)
E=[ones(1,hA);zeros(1,hA)]
F=flipud(E)
G=A*C % = repmat(A(:,1),1,hB)
H=A*D % = repmat(A(:,2),1,hB)
I=B*E % = repmat(B(:,1),1,hA)
J=B*F % = repmat(B(:,2),1,hA)
d=sqrt((G-I').^2+(H-J').^2)
end
The previous code that work only for 2 dimensions is given here for historical purposes.
function d=dist(A,B)
% DIST return distance matrix between point A=[x1 y1] and B=[x2 y2]
% Number of points in A and B are not necessarily the same.
% It can be use for distance-in-a-slice, distance-between-slice,
% and distance between guest-points-and-the-points
% A and B must contain two columns,
% first column is the X coordinates
% second column is the Y coordinates
% The distance matrix are distance between points in A as row
% and points in B as column.
% example: distance-in-a-slice= dist(A,A)
% distance between guest-point-and-the-point = dist(A,B) , hA=hB
% distance between slices = dist(A,B), with hA ~= hB or hA=hB
% A=[1 2; 3 4; 5 6]; B=[4 5; 6 2; 1 5; 5 8]
% dist(A,B)= [ 4.24 5.00 3.00 7.21;
% 1.41 3.61 2.24 4.47;
% 1.41 4.12 4.12 2.00 ]
[hA,wA]=size(A)
[hB,wB]=size(B)
if hA==1& hB==1
d=sqrt(dot((A-B),(A-B)));
else
C=[ones(1,hB);zeros(1,hB)]
D=flipud(C)
E=[ones(1,hA);zeros(1,hA)]
F=flipud(E)
G=A*C % = repmat(A(:,1),1,hB)
H=A*D % = repmat(A(:,2),1,hB)
I=B*E % = repmat(B(:,1),1,hA)
J=B*F % = repmat(B(:,2),1,hA)
d=sqrt((G-I').^2+(H-J').^2)
end

0 Comments:
Post a Comment
<< Home