maxk

The k largest elements of an array, in descending order.

Category: Data Import and Analysis > Descriptive Statistics

Syntax

B = maxk(A, k)

The k largest values along the first non-singleton dimension.

B = maxk(A, k, dim)

Along dimension dim.

[B, I] = maxk(___)

Also returns the indices of those values in A.

Description

maxk gives the top k without sorting the whole array by hand. The result keeps the orientation of the operation: for a row vector it is a row, and for a matrix it holds the top k of each column.

If k is larger than the number of elements, all elements are returned.

Input arguments

A
Numeric array.
k
How many values to return.
dim
Dimension to operate along.

Output arguments

B
The k largest values, sorted from largest to smallest.
I
Indices into A of the values in B.

Example

Top three values

x = [3 1 4 1 5 9 2 6 5 3];
[B, I] = maxk(x, 3)
Output
B = 1×3

     9     6     5
I = 1×3

     6     8     5

See also

mink max sort bounds