f = 1; for i=1:sum(b) g=b; g(f)=0; [e,f]=max(g); c(i)=a(f); c=[]; while any(b) [e,f]=max(b); c=[c e]; b(f)=b(f)-1; end