This is because you potentially find more than one cluster that have the same distance to the query point. find defines all values ββthat satisfy the logical condition as an argument. idx(i) implies that you assign a single value to the idx array, but find can give more than one value, and this gives the assignment error that you see.
Instead, use the second output argument min , which defines the index for the first time , the smallest value that you want to execute:
function idx = findClosestCentroids(X, centroids) K = size(centroids, 1); idx = zeros(size(X,1), 1); dist = zeros(K, 1); for i = 1:size(X,1) for j = 1:K dist(j) = sum((X(i,:) - centroids(j,:)).^2); end [~,idx(i)] = min(dist); %
source share