#!/usr/bin/Rscript a <- c(2, 10, 1, 5, 8, 4, 5, 8, 7, 5, 6, 4, 2, 2, 4, 9) dim(a) <- c(2,8) a <- t(a) plot(a, col=1:8, pch=19) text(a[,1]+0.15, a[,2]+0.15, 1:8) print(dist(a)) print(dist(a) ^ 2) centers <- a[c(1,4,7),] step <- 0 while(TRUE) { d <- as.matrix(dist(rbind(a,centers)))[9:11,-(9:11)] mapping <- apply(d, 2, which.min) cat("step", step, ":\n") cat("cluster mappings:\n") print(mapping) plot(a, col=mapping, pch=19) text(a[,1]+0.15, a[,2]+0.15, 1:8) cat("centers:\n") print(centers) points(centers, pch=4, col=1:3) Sys.sleep(1) new_centers <- t(sapply(1:3, function(i) c(mean(a[which(mapping == i),1]), mean(a[which(mapping == i),2])))) if(!sum(new_centers != centers)) break centers <- new_centers step <- step + 1 }