Re-sort using second output of sort in Matlab

Alec Jacobson

November 15, 2011

weblog/

Matlab's sort function gives you a secondary output which can be used to resort your matrix. If you're sorting each row of an m by n matrix V then:
[SV,I] = sort(V,2);
gives you the m by n indexing matrix I which for each rows tell the ordering of V needed to produce the corresponding row in SV To reproduce the sort of the entire matrix again you can use
reSV = V(sub2ind(size(V),repmat(1:size(V,1),size(V,2),1)',I));