Search code examples
matlabsortinglexicographic

Lexicographic ordering of triplets of integers in Matlab


I have the following problem: I have an array of N integer triplets (i.e. an Nx3 matrix) and I would like to order it lexicographically in Matlab. In order to do so I thought of using the built-in sort algorithm of Matlab, but I wanted to ask if the way I thought of doing it is right or if there exists a simpler way (preferably using Matlab routines).

I thought of converting every triplet into a single number and then sort these numbers with sort(). If my integers were between 0 and 9, I could just convert them into decimal. However, they are bigger. If their maximum absolute value is M, I thought of converting them into the (M+1)-ary system like this: if (a,b,c) the triplet, the corresponding integer is a*(M+1)^2+b*(M+1)+c. Would sorting these transformed integers solve the problem, or am I making a logical mistake in my reasoning?

Thank you!

PS: I know that sort() in Matlab does have a lexicographic option for strings, but my integers do not have the same digit length. Maybe padding them with leading zeros and concatenating them would do the trick?


Solution

  • Have you considered using sortrows?
    Should enable you to straight-forward sort your 3-columns of data lexicographically.