Sorting
is a concept in which elements are rearranged logically into a pattern where numbers either go from smaller to larger, or from larger to smaller numbers.
There are many algorithms we can use for sorting, but in MATLAB, we can sort an array or matrix of numbers in MATLAB using the built-in function. MATLAB has a simple sort()
function that sorts a list of elements in ascending order
or descending order
based on the condition specified.
Ascending order
The list specified inside the sort function
is sorted in an ascending order. We can also specify the dimension
alongwith the array we want to sort. It can either be column-wise
or row-wise.
By default, MATLAB sorts column-wise
. We have to specify row wise
if we wish to do so. Let’s look at the syntax:
// assume list_num is a list of numbers
Sorted = sort(list_num,dim)
Here, two arguments are given to the sort()
function. First is the array
or the object we want to sort and the second is the dimension
along which we want to sort.
MATLAB uses two dimensions arguments for sorting. If we put dim=1
, sorting is done along columns. If we put dim = 2
, sorting is done along rows
.
The sort()
function can sort one dimensional lists
, otherwise known as vectors
in MATLAB by simply sorting the row.
one_dimensional = [4 1 5 2 3 9 7];
sorted = sort(one_dimensional)
// answer will be
// [1 2 3 4 5 7 9]
In one dimensional vectors, since there is one column, MATLAB sorts row-wise
. We don’t need to specify the dimension
here. We can specify the dimension here but it is of no use.
The sort()
function can sort multi dimensional arrays
in MATLAB by sorting the elements column wise
. If we wish to do row-wise
sorting, we’ll have to specify this.
// Column Wise Sorting
matrx = [9 1 3;
5 4 2;];
sorted = sort(matrx)
// answer will be calculated by column-wise sorting
// [ 5 1 2;
// 9 4 3];
// Row Wise Sorting
matrx = [9 1 3;
5 4 2;];
sorted = sort(matrx,2)
// answer will be calculated by row-wise sorting
// [ 1 3 9;
// 3 4 5];
string
arrayThe MATLAB sort()
can further be extended to sort arrays or vectors of strings
. As in the case with the numbers, we can sort in both a column-wise
and row-wise
manner by specifying the dimension. Strings are sorted based on the ASCII
value of the first character in ascending order
. See the sample below:
//Sorting Column Wise
string_arr = ["Jake" "Harry";
"Zio" "Ben";];
sorted = sort(string_arr)
//answer will be
// ["Jake" "Ben"
// "Zio" "Harry"]
//Sorting Row Wise
string_arr = ["Jake" "Harry";
"Zio" "Ben";];
sorted = sort(string_arr,2)
//answer will be
// [ "Harry" "Jake"
// "Ben" "Zio" ]
Descending Order
MATLAB allows sorting in descending order
. We just have to specify the keyword 'descend'
in the code, and the rest is done by MATLAB.
list_arr = [1 4 5 9 6,11];
sorted = sort(list_arr, 'descend')
// answer will be
// [11 9 6 5 4 1]