Path: news.mathworks.com!not-for-mail
From: "Jos " <DELjos@jasenDEL.nl>
Newsgroups: comp.soft-sys.matlab
Subject: Re: The N largest values of an M x 1 matrix
Date: Thu, 3 Jan 2008 19:49:46 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 53
Message-ID: <flje8q$bdd$1@fred.mathworks.com>
References: <57537254-3f7e-43e4-8fc4-75d8de63b3d6@s8g2000prg.googlegroups.com>  <7222b5d8-b1b3-425c-be43-ac349257c5e7@e23g2000prf.googlegroups.com>
Reply-To: "Jos " <DELjos@jasenDEL.nl>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1199389786 11693 172.30.248.37 (3 Jan 2008 19:49:46 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 3 Jan 2008 19:49:46 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 870065
Xref: news.mathworks.com comp.soft-sys.matlab:444243


Palle Uldenborg <palle.uldenborg@gmail.com> wrote in 
message <7222b5d8-b1b3-425c-be43-
ac349257c5e7@e23g2000prf.googlegroups.com>...
> On Jan 3, 3:39 pm, "Jos " <DEL...@jasenDEL.nl> wrote:
> > Palle Uldenborg <palle.uldenb...@gmail.com> wrote in 
message
> > <57537254-3f7e-43e4-8fc4-
75d8de63b...@s8g2000prg.googlegroups.com>...
> > > I would like to find the indexes of the N largest 
elements of an   M x
> > > 1 matrix. right now I do something lik the following, 
but
> > > it doesn't scale well.
> > > N=10;M=100;a=rand(1,M);[val,ip]=sort(a);idx=ip(end-
N:end);a(idx)
> > > Does matlab have a specialized function for this?
> > What do you mean by "it doesn't scale well"?
> 
> Thank you for your answer. Sorry if I was unclear.
> 
> I meant that for for a fixed value of N the CPU cost does 
not scale
> linearly with M.
> 
> I am interested in situations such as N=5 and M=100000, 
so I think
> that I could gain from a matlab function that did some 
kind of partial
> sorting.
> 
>                        Niels
> 
> 
> 
> 
> 


For N << M, this may be faster then using sort

M = 1000000 ;
N = 5 ;
A = rand(M,1) ;

val(1:N) = NaN ;
for j=1:N,
   [val(j),ind] = max(A) ;
   A(ind) = -Inf ;
end


hth
Jos