Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to make the following case vectorized?
Date: Thu, 5 Jun 2008 21:18:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 62
Message-ID: <g29l69$90t$1@fred.mathworks.com>
References: <g26qnb$4nt$1@fred.mathworks.com> <g29f1d$ra2$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1212700681 9245 172.30.248.38 (5 Jun 2008 21:18:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 5 Jun 2008 21:18:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 870065
Xref: news.mathworks.com comp.soft-sys.matlab:472440



"Roger Stafford" 
<ellieandrogerxyzzy@mindspring.com.invalid> wrote in 
message <g29f1d$ra2$1@fred.mathworks.com>...
> "James Anderson" <janderson_net@yahoo.com> wrote in 
message <g26qnb
> $4nt$1@fred.mathworks.com>...
> > Hi, 
> > 
> > I have a matrix (say 10000 rows and 50 columns). I want 
to
> > find the rank for each entry within the row it belongs 
to. I
> > know how to do this by using a loop, suppose A is the 
matrix
> > 
> > for k = 1:10000;
> >   [sortx,ind] = sort(A(k,:));
> >   rankt(ind) = 1:50;
> >   Rank(k,:) = rankt;
> > end
> > 
> > The Rank contains what I need. However, this is going to
> > take a long time, especially when the number of rows get
> > even larger. I found the function sort can sort the 
whole
> > matrix along one direction, however, is there any 
vectorized
> > way to get the Rank very fast without doing any 
looping? 
> > 
> > Thanks,
> > 
> > James
> --------------
>   Here is a way that avoids a second sort, though I don't 
know if it's any faster 
> than Walter's.  It depends on how large n is.  The sort 
would be of order 
> m*n*log(n) for large n, as against order m*n for the last 
two lines below.
> 
>  [m,n] = size(A);
>  [ig,ind] = sort(A,2);
>  [r,Rank] = ndgrid(1:m,1:n);
>  Rank(r+m*(ind-1)) = Rank;
> 
> Roger Stafford
> 
> 


and a solution that avoids ndgrid as well as a seconc call 
to sort:

[m,n] = size(A);
[ig,ind] = sort(A,2);
Rank3 = ind + repmat(n*(0:m-1),n,1).' ;
Rank3(Rank3) = repmat(1:n,m,1) ;
Rank3 = reshape(Rank3,[],m).' ;

hth
Jos