miremehr
miremehr

Reputation: 67

GNU Octave: How to find n maximum elements of a vector

I have vector in Octave like this:

[ 4 5 1 2 3 6 ]

Is there any function that returns n maximum elements of that vector, in this case, the three biggest are 6, 5, and 4?

[6 5 4]

The Octave max function only returns one maximum element. I want n maximum elements.

Upvotes: 4

Views: 3602

Answers (2)

Eric Leschinski
Eric Leschinski

Reputation: 154063

In GNU Octave, get the biggest n elements of a vector:

octave:2> X = [3 8 2 9 4]
octave:2> sort(X)

ans =
   2   3   4   8   9

octave:8> sort(X)(end-2:end)

ans =

   4   8   9

Description

What sort(X)(end-2:end) means is "sort the vector X, and give me the elements from 2 minus the end to the end, also known as the last 3 elements".

Upvotes: 5

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

You can use the sort function for this.

Upvotes: 4

Related Questions