📄 k_means.m
字号:
function [gIdx,c]=k_means(X,k)
% Check input and output number of arguments
error(nargchk(2,2,nargin));
error(nargoutchk(0,2,nargout));
[n,m]=size(X);
% Check if second input is centroids else generate the centers randomly
if ~isscalar(k)
c=k;
k=size(c,1);
else
c=X(ceil(rand(k,1)*n),:);
end
% allocating variables
g0=ones(n,1);
gIdx=zeros(n,1);
D=zeros(n,k);
% Main loop converge if previous partition is the same as current
while any(g0~=gIdx)
% disp(sum(g0~=gIdx))
g0=gIdx;
% Loop for each centroid
for t=1:k
d=zeros(n,1);
% Loop for each dimension
for s=1:m
d=d+(X(:,s)-c(t,s)).^2;
end
D(:,t)=d;
end
% Partition data to closest centroids
[z,gIdx]=min(D,[],2);
% Update centroids using means of partitions
for t=1:k
c(t,:)=mean(X(gIdx==t,:));
end
% for t=1:m
% c(:,t)=accumarray(gIdx,X(:,t),[],@mean);
% end
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -