topkrows

Returns the k rows of a matrix or table with the largest values.

Category: Language Fundamentals > Data Types

Syntax

B = topkrows(A, k)

Returns the k rows with the largest values in the first column, in descending order.

B = topkrows(A, k, col)

Ranks by column col instead of the first.

Description

topkrows(A, k) is the same as the first k rows of sortrows(A, 1, 'descend'), but written for the common case of picking a few best items from a large set. Whole rows move together, so the values in other columns stay attached to their ranking value.

If k is larger than the number of rows, all rows are returned in sorted order.

Input arguments

A
Numeric matrix, or table.
k
Number of rows to return.
col
Column (or variable) used to rank the rows.

Output arguments

B
k rows of A, largest first.

Example

Top rows by first and second column

A = [3 1; 9 2; 5 7; 1 4];
topkrows(A, 2)
topkrows(A, 2, 2)
Output
ans = 2×2

     9     2
     5     7
ans = 2×2

     5     7
     1     4

See also

sortrows maxk sort max