SORTSET (v2.0)

Sort a set according to a user-defined order
2.1K Downloads
Updated 20 Oct 2008

View License

SORTSET Sort a set according to a user-defined order

For vectors, R = SORTSET(S,ORDER) sorts a set S according to the order specified by ORDER. If elements of S are not present in ORDER they will be put at the end of R in the original order.
For matrices, SORTSET(S,ORDER) sorts each column of S, and for N-D arrays, SORTSET(S,ORDER) sorts the elements along the first non-singleton dimension of S.

SORTSET(S,ORDER,DIM) sorts along the dimension DIM.

[R, I, J] = SORTSET(S, ORDER) returns index vectors so that R equals S(I), and R(J) equals S. R, I, and J have the same size as S.

S and ORDER can be cell arrays of strings.

Examples:
% Sort numbers in a self-defined order: first 80-100, than reverse
% odd first, than rest
S = ceil(rand(1,10)*100) % 10 random numbers
ORDER = [80:100 99:-2:1 1:100] ;
R = sortset(S,ORDER)

% sort a list of words (with the word 'xxx' not in the list)
S = {'bb','a','dd','a','cc','dd','xxx','cc','e','bb'}
[R,I,J] = sortset(S, {'a','e','bb','dd','cc'})
isequal(R,S(I)), isequal(R(J),S)

% sort the list of words along columns
S = {'bb','a','dd','a','cc' ; 'dd','dd','cc','e','bb'}
R = sortset(S,{'a','e','bb','dd','cc'},2)

Notes:
- If an element occurs multiple times in ORDER, the first occurence is taken as its rank. For instance, when ORDER is [20 13 1 13] and S is [13 1] the result will be [13 1] and not [1 13].
- The functionality is similar to, but more convenient than something like:
S = {'bb','a','dd','a','cc','dd','dd','cc','e','bb'}
Ranks = [3 1 4 1 5 4 4 5 2 3] ;
[SRanks, si] = sort(Ranks) ; R2 = S(si)

Cite As

Jos (10584) (2024). SORTSET (v2.0) (https://www.mathworks.com/matlabcentral/fileexchange/21762-sortset-v2-0), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R14
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Shifting and Sorting Matrices in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.0.0.0

(v2.0) changed towards similar functionality as SORT, checked textual errors