isort
Syntax
isort(X, [ascending=true])
Arguments
X is a vector or a tuple of vectors of the same length.
ascending is a Boolean scalar or vector indicating whether to sort X (or vectors of X sequentially) in ascending order or descending order. The default value is true (ascending order).
Details
Instead of returning a sorted vector like sort!, isort
returns the indexes in
the original vector for each element in the sorted vector.
X[isort X]
is equivalent to sort!(X)
.
Examples
x = 4 1 3 2;
y = isort(x);
y;
// output
[1,3,2,0]
// for the sorted x: [1 2 3 4], the first element 1 is from position 1 of the original x, the second element 2 is from position 3 of the original x, ... etc.
x[y];
// output
[1,2,3,4]
// equivalent to sort!(x)
z=isort(x, false);
z;
// output
[0,2,3,1]
x[z];
// output
[4,3,2,1]
x=2 2 1 1
y=2 1 1 2
isort([x,y]);
// output
[2,3,1,0]
isort([x,y],[0,0]);
// output
[0,1,3,2]
Sort a table based on one of its columns:
t2 = table(4 2 3 1 as x, 9 6 7 3 as y);
t2;
x | y |
---|---|
4 | 9 |
2 | 6 |
3 | 7 |
1 | 3 |
t2[isort(t2.x)];
x | y |
---|---|
1 | 3 |
2 | 6 |
3 | 7 |
4 | 9 |
t2[isort(t2.x, false)];
x | y |
---|---|
4 | 9 |
3 | 7 |
2 | 6 |
1 | 3 |
Sort a table based on multiple columns:
a=5 5 5 3 3 8 7 7;
b=`MSFT`GOOG`IBM`YHOO`X`YHOO`C`ORCL;
t=table(a,b);
t;
a | b |
---|---|
5 | MSFT |
5 | GOOG |
5 | IBM |
3 | YHOO |
3 | X |
8 | YHOO |
7 | C |
7 | ORCL |
t[isort([a,b], false true)];
// first sort descending on a, then sort ascending on b
a | b |
---|---|
8 | YHOO |
7 | C |
7 | ORCL |
5 | GOOG |
5 | IBM |
5 | MSFT |
3 | X |
3 | YHOO |
t[isort([a,b], false)];
// equivalent to t[isort([a,b], false false)];
a | b |
---|---|
8 | YHOO |
7 | ORCL |
7 | C |
5 | MSFT |
5 | IBM |
5 | GOOG |
3 | YHOO |
3 | X |