// Jun 27 2017 11:41:08
// Given a medoids var (binary indicator), create a group var
// Reverse of getmedoids

program getgroup
syntax varlist(min=1 max=1), DISTmat(string) IDvar(varname) GENerate(string)
// Insist on sort oder
qui isid `idvar', sort

di "Creating `generate' variable as groups nearer to medoids in `varlist'"
mata: getgroup("`distmat'", "`varlist'", "`generate'")
end

capture mata mata drop getgroup()
mata
real matrix getgroup (string mat, string medind, string newvar) {
  dist = st_matrix(mat)
  N = rows(dist)
  st_view(medbin=.,., (medind))
  medoids = select(range(1,N,1), medbin)

  nearestvalue = rowmin(dist[.,medoids])
  nearestcase  = dist[.,medoids] :== nearestvalue
  group = rowmax(nearestcase:*transposeonly(range(1,length(medoids),1)))
  idx = st_addvar("double",newvar)
  View = .
  st_view(View,.,idx)
  View[1..N,.] = group
}
end