lettura simple

How to sort an array in Octave

In this lesson I'll explain how to sort in ascending or descending order the elements of an array in Octave.

I'll give you a practical example.

Make a vector with 5 elements.

>> v = [ 4 2 1 6 3 5 ]
v =
4 2 1 6 3 5

Vector elements are not sorted.

To sort the elements of the vector in ascending order use the function sort(v)

This function outputs the vector with the values sorted in ascending order.

>> sort(v)
ans =
1 2 3 4 5 6

If you want to sort the elements of the vector in descending order, add the word 'descend' in the second parameter

>> sort(v, 'descend')
ans =
6 5 4 3 2 1

You can also use the sort() function to sort arrays with multiple dimensions.

For example, create a matrix (two-dimensional array)

>> M = [ 1 4 1 ; 2 8 3 ; 5 1 6 ]
M =
1 4 1
2 8 3
5 1 6

Now type the function sort().

The function returns the same matrix with all elements in ascending order.

>> sort(M)
ans =
1 1 1
2 4 3
5 8 6




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin