Path: news.mathworks.com!newsfeed-00.mathworks.com!news.kjsl.com!newsfeed.stanford.edu!elk.ncren.net!newsflash.concordia.ca!canopus.cc.umanitoba.ca!not-for-mail
From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Newsgroups: comp.soft-sys.matlab
Subject: Re: Array manipulation question
Date: Tue, 21 Aug 2007 18:45:15 +0000 (UTC)
Organization: National Research Council Canada - Conseil national de rechereches Canada
Lines: 33
Message-ID: <fafbrr$l95$1@canopus.cc.umanitoba.ca>
References: <fafah8$ot$1@fred.mathworks.com>
NNTP-Posting-Host: origin.ibd.nrc.ca
X-Trace: canopus.cc.umanitoba.ca 1187721915 21797 192.70.172.160 (21 Aug 2007 18:45:15 GMT)
X-Complaints-To: abuse@cc.umanitoba.ca
NNTP-Posting-Date: Tue, 21 Aug 2007 18:45:15 +0000 (UTC)
Originator: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Xref: news.mathworks.com comp.soft-sys.matlab:424825



In article <fafah8$ot$1@fred.mathworks.com>,
Adam  <crossroads_evh.nospam@hotmail.com> wrote:
>   I'm looking for a way to have Matlab return some number 
>(N) of the smallest elements in an array along with their 
>indices in the array.  For example, given the array:

>[5 4 3 2 1] and N = 3

>The output should be something like:
>
>[[3 3],[2 4],[1 5]]

>This can be done with brute force but I'm looking for a 
>cleaner implementation.  I can't use the sort function 
>because it re-orders the array and I would lose the index 
>information.

A = [5 4 3 2 1];
N = 3;

[sortedvec, sortidx] = sort(A);
origorder = sort(sortidx(1:N));
result = [A(origorder);origorder]'

result =

     3     3
     2     4
     1     5

-- 
  There are some ideas so wrong that only a very intelligent person
  could believe in them.                              -- George Orwell