help-octave
[Top][All Lists]

## RE: sort question

 From: Ted Harding Subject: RE: sort question Date: Wed, 05 May 2004 08:48:13 +0100 (BST)

```On 05-May-04 Michael Underwood wrote:
> I looking for a neat way of determining the index that of each element
> of an array would have if sorted.
>
> eg.
> octave:1> a = rand(4,1)
> a =
>
>   0.73433
>   0.55564
>   0.49191
>   0.90766
>
> octave:2> b= sort(a)
> b =
>
>   0.49191
>   0.55564
>   0.73433
>   0.90766
>
> for instance, a(1)  is the 3rd element of b.
>
> I know this can be done with the find command, but the array I am
> dealing with are sufficiently large to make the find command too time
> consuming.

I think this does what you are looking for:

octave:5> X=[3,2,1,6,4,5]
X =
3  2  1  6  4  5

octave:6> [Y,ix]=sort(X)
Y =
1  2  3  4  5  6

ix =
3  2  1  5  6  4

octave:7> [y,iy]=sort(ix)
y =
1  2  3  4  5  6

iy =
3  2  1  6  4  5

See "help(sort)". When you give two output arguments [Y,ix],
the first (Y) is the sorted vector; the second (ix) is the
set of indices such that X(ix) = Y, i.e. it is the permutation
that does the sorting: X((ix(i)) = Y(i).

What you are looking for is the inverse of this permutation,
so if you sort (ix) and look at the permutation index for
this sort, you will find what you are looking for, since
sorting (ix) takes it back to (1,2,3,...).

Hope this helps!
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <address@hidden>
Fax-to-email: +44 (0)870 167 1972
Date: 05-May-04                                       Time: 08:48:13
------------------------------ XFMail ------------------------------

-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.octave.org
How to fund new projects:  http://www.octave.org/funding.html
Subscription information:  http://www.octave.org/archive.html
-------------------------------------------------------------

```

reply via email to