Path: news.mathworks.com!not-for-mail
From: "Steven Lord" <slord@mathworks.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: sorting, ranking
Date: Fri, 21 Aug 2009 12:56:04 -0400
Organization: The MathWorks, Inc.
Lines: 56
Message-ID: <h6mjir$ji9$1@fred.mathworks.com>
References: <h6mh83$j42$1@fred.mathworks.com>
Reply-To: "Steven Lord" <slord@mathworks.com>
NNTP-Posting-Host: lords.dhcp.mathworks.com
X-Trace: fred.mathworks.com 1250873755 20041 172.31.44.65 (21 Aug 2009 16:55:55 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 21 Aug 2009 16:55:55 +0000 (UTC)
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.5512
X-RFC2646: Format=Flowed; Original
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5579
Xref: news.mathworks.com comp.soft-sys.matlab:565122



"Wyatt " <hello@hello.com> wrote in message 
news:h6mh83$j42$1@fred.mathworks.com...
> 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.

*snip*

> If I then sort these numbers

*snip*

> and wish to obtain their ranking

*snip*

> 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:

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sort.html

"[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
slord@mathworks.com