08-16-2017, 08:49 PM
I am doing a project on realization of clustering using k-means algorithm.
Can any one help me to realize the following matlab codes,how it works,specifications and detail explanations regarding the code functions and its implementations, please help me out.
1.
function d=DistMatrix(A,B)
[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©;
E=[ones(1,hA);zeros(1,hA)];
F=flipud(E);
G=A*C;
H=A*D;
I=B*E;
J=B*F;
d=sqrt((G-I').^2+(H-J').^2);
end
2.
function y=kMeansCluster(m,k,isRand)
m=[ 1 1; 2 1; 4 3; 5 4],k=2
if nargin<3, isRand=0; end
if nargin<2, k=2; end
[maxRow, maxCol]=size(m)
if maxRow<=k,
y=[m, 1:maxRow]
else
% initial value of centroid
if isRand,
p = randperm(size(m,1)); % random initialization
for i=1:k
c(i,=m(p(i),
end
else
for i=1:k
c(i,=m(i, % sequential initialization
end
end
temp=zeros(maxRow,1); % initialize as zero vector
while 1,
d=DistMatrix(m,c); % calculate objcets-centroid distances
[z,g]=min(d,[],2); % find group matrix g
if g==temp,
break; % stop the iteration
else
temp=g; % copy group matrix to temporary variable
end
for i=1:k
f=find(g==i);
if f % only compute centroid if f is not empty
c(i,=mean(m(find(g==i),,1)
end
end
end
y=[m,g];
end