Fraukje
Fraukje

Reputation: 683

Select n biggest value in array in oneliner

For no particular reason I would like to know if it's possible to select the n number of biggest value in an array or matrix, all in a oneliner.

Say I have array:

A=randn(1,100);

And I want the biggest, e.g., 20 values, preferably ordered from high to low. So far I have the 2-liner:

A_ordered = sort(A,'descend');
A_big20 = A_ordered(1:20);

Does anyone know if this is possible in one line? If so, I would appreciate clues, ideas or an answer!

Upvotes: 2

Views: 130

Answers (3)

Shai
Shai

Reputation: 114816

You can use prctile:

a = randn(1,100);
n = 10;
topn = sort( a( a > prctile( a, 100 *( 1 - n/numel(a) ) ) ) )

Upvotes: -1

Robert Seifert
Robert Seifert

Reputation: 25232

For my opinion getfield is everything than "dirty" (though listed in the link by Amro). But he is right, it's slower than a simple two-line solution. If you insist for the sake of beauty, here we go:

A20 = getfield(sort(A,'descend'),{1:20})

Upvotes: 4

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

you say you do this a lot, so the easiest and best way is to define a function on the MATLAB path:

function B = topN(A, n)

    if nargin==2 && n==0 
        B = []; return; end

    B = sort(A(:));
    if nargin>1 && n < numel(A)           
        B = B(1:n); end

end

and call your "one" liner:

top_ten = topN( randn(1,100), 10 );

If you want them to be in the original order (instead of sorted):

function B = topN_unsorted(A, n)

    if nargin>1 && n==0 
        B = []; return; end

    if nargin==1 || n > numel(A)
        B = A; 
    else
        [B,I] = sort(A(:));
        B = B(I(1:n));
    end

end

Upvotes: 5

Related Questions