Machine Learning Week8 findClosestCentroids.m

来源:互联网 发布:网络算法与复杂性理论 编辑:程序博客网 时间:2024/05/19 18:42

增加一个临时变量dist记录当前最短的距离
loop over centroids计算属于哪一个聚类中心。

function idx = findClosestCentroids(X, centroids)%FINDCLOSESTCENTROIDS computes the centroid memberships for every example%   idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids%   in idx for a dataset X where each row is a single example. idx = m x 1 %   vector of centroid assignments (i.e. each entry in range [1..K])%% Set KK = size(centroids, 1);% You need to return the following variables correctly.idx = zeros(size(X,1), 1);% ====================== YOUR CODE HERE ======================% Instructions: Go over every example, find its closest centroid, and store%               the index inside idx at the appropriate location.%               Concretely, idx(i) should contain the index of the centroid%               closest to example i. Hence, it should be a value in the %               range 1..K%% Note: You can use a for-loop over the examples to compute this.%dist = 100*ones(size(X,1),1);for i = 1:K    cent = centroids(i,:);    cent = repmat(cent,size(X,1),1);    curdist = sum((X-cent).^2,2);    ind = curdist<dist;    dist(ind) = curdist(ind);    idx(ind) = i;end% =============================================================end
1 0
原创粉丝点击