*Just one idea to do hierarhical (nested) sorting in MATRIX-END MATRIX.
*The code below sorts rows of matrix by values of all its columns, each column within identical values of preceeding column.
*The SORT CASES command that will correspond to the syntax is
*SORT CASES BY v1(A) v2(A) v3(D) v4(A) v5(D).
* Author: Kirill Orlov email: kior@comtv.ru
* Date: 2010/04/09 .
set mxloops 1000.
matrix.
comp mat= rnd(uniform(50,5)*10). /*Let's generate some matrix of 5 columns (variables)
print mat /title 'Original'.
comp ord= {1,1,-1,1,-1}. /*What order of sorting you want for each column: 1=ascending, -1=descending
comp mat(grade(ord(1)*mat(:,1)),:)= mat. /*Do sort rows by values of column 1
loop i= 2 to ncol(mat). /*Do sort rows by values of each successive column within identical values of preceeding columns
-comp lst= 0. /*'fst' is row number where value begins, 'lst' - where it ends, in the column last sorted
-loop. /*For each unique value in that sorted column
- comp fst= lst+1. /*find 'fst'
- loop lst= fst to nrow(mat)-1. /*and 'lst'
- end loop if any(mat(lst+1,1:(i-1))<>mat(lst,1:(i-1))). /*Important: the value series from 'fst' to 'lst' in that column should imply
/*that all even earlier sorted columns should each have just one value for rows 'fst' to 'lst'
- comp mat(grade(ord(i)*mat(fst:lst,i))+fst-1,:)= mat(fst:lst,:). /*Having found 'fst' è 'lst', sort rows 'fst' to 'lst' of the current column i
-end loop if lst=nrow(mat). /*Now turn for next unique value in last sorted column i-1
end loop. /*All columns done
print mat /title 'Rows sorted'.
end matrix.
*Sorting columns is same algo (easy to rewrite) or just transpose your matrix and use the above.
*It is possible to modify the code so that one be able to sort rows by columns selected in the matrix and in arbitrary sequence
*rather than sort by all of the columns and in their natural sequence (as the above code does). However I feel
*it might make the code a bit corpulent, so it seems easier to extract the columns of interest as a separate matrix, sort
*it by the code above and then insert back into the parent matrix on their positions.