find nth max

  • Follow


Hi,
I have a large matrix, and I will like to find the 100th largest value. I tried this code but it seems to be slow and take a lot of memory. Any better way?
 
  poki=rand(1,5e6);
   Anum=100;
   for count=1:Anum,
       [yoki,Aindex]=max(poki); 
       poki(Aindex)=0;
   end;


Thanks! Matt
0
Reply Matt 12/5/2009 5:23:03 AM

Why not:

% Data
poki = rand(1,5e6);

% Engine
one_hund_max = sort(poki);
one_hund_max = one_hund_max(100)

Alternatively there is a file on the FEX by Bruno Luong which does this, perhaps with more efficiency.  I haven't tried it myself but Bruno does good work, it might be worth checking out:

http://www.mathworks.com/matlabcentral/fileexchange/23576-minmax-selection
0
Reply Matt 12/5/2009 5:38:04 AM


Some timings on my machine of three methods:

timings (s):
	 for-loop=1.013391
	 sort=0.505660
	 maxk=0.110003

Benchmark function I used:

function benchmax

A=randn(1,5e6);
Anum=100;

%%%%%%%%%%%%
tic
poki = A;
for count=1:Anum,
    [yoki,Aindex]=max(poki);
    poki(Aindex)=-inf;
end
t1=toc;
yoki
clear Aindex poki

%%%%%%%%%%%%
tic
taki = sort(A);
taki = taki(end-Anum+1);
t2=toc;
taki

%%%%%%%%%%%%
tic
koko = maxk(A, Anum);
koko = koko(end);
t3=toc;
koko

fprintf('timings (s):\n\t for-loop=%f\n\t sort=%f\n\t maxk=%f\n', t1, t2, t3);

% Bruno
0
Reply b.luong5955 (6341) 12/5/2009 8:45:18 AM

On 5 Des, 06:23, "Matt Fetterman" <mattinjer...@yahoo.com> wrote:
> Hi,
> I have a large matrix, and I will like to find the 100th largest value. I tried this code but it seems to be slow and take a lot of memory.

You need to sort the matrix. Use an efficient sorting
algorithm. As for space, you need a vector of the same
number of indexes as the number of elements in your
matrix.

> Any better way?

Do an indirect sort:

1) Set up a vector of indexes to the matrix
2) Sort this sequence of indexes acording
   to the corresponding element in the matrix
3) Pick out the 100th element trough the sorted
   index vector.

It's more or less what matlab's SORT already does,
except one only computes the index vector IX (the #2
returned result) and not the sorted matrix itself
(the #1 returned result), which might save space.
You could save a lot more space if you select the
data types for the index vector carefully.

Rune
0
Reply allnor (8474) 12/5/2009 4:12:08 PM

3 Replies
1409 Views

(page loaded in 0.053 seconds)

Similiar Articles:













7/20/2012 9:35:15 AM


Reply: