The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: sorting, ranking
Replies: 10   Last Post: Jan 14, 2013 1:25 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Steven Lord

Posts: 18,038
Registered: 12/7/04
Re: sorting, ranking
Posted: Aug 21, 2009 12:56 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

"Wyatt " <> wrote in message
> Hello All,
> I have encountered some weird behavior with matlab when attempting to rank
> a list of numbers.
> lets assume that I generate a vector of random numbers.


> If I then sort these numbers


> and wish to obtain their ranking


> I should get back a permutation of the vector temp in terms of the ordered
> indices of sorted values from A, instead this code simply returns the I
> vector
> the correct execution of the command rank = temp(I) should return
> rank = [7 10 3 1 8 9 4 6 5 2]
> Am I missing something here, or mistaken about how matlab should behave in
> this case? Or is there simply a bug?

You have it backwards. You want "rank(I) = temp" instead.

S = 100*rand(1, 10)
[value, order] = sort(S)
restoreS(order) = value
isequal(restoreS, S)

From the reference page:

"[B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) ==
size(A). If A is a vector, B = A(IX)." [or exchanging the two sides of the
equation, A(IX) = B.]

So the 1st element of B, the sorted array, corresponds to element IX(1) in
A -- and that's the assignment you need to make to "undo" the sorting. To
generalize, B(k) corresponds to A(IX(k)), or if you vectorize newA(IX) = B
undoes the sort and makes A and newA agree.

Steve Lord

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.