Sorting By Functions in Scilab
Our example demonstrates custom sorting in Scilab. We’ll sort strings by their length and then sort a list of custom structures.
In this Scilab example, we first sort a list of fruits by their length. We define a custom comparison function lenCmp
that compares the lengths of two strings. We then use Scilab’s gsort
function with the “g” option, which allows us to provide a custom comparison function.
Next, we define a Person
structure with name
and age
fields. We create a list of Person
structures and sort them by age. We define another custom comparison function ageCmp
that compares the ages of two Person
structures.
The gsort
function in Scilab is versatile and can sort various data types, including structures, using custom comparison functions. This is similar to the slices.SortFunc
function in the original example.
Note that Scilab doesn’t have built-in support for object-oriented programming like some other languages, so we use structures to represent our Person
objects.
To run this program, save it as a .sce
file (e.g., custom_sort.sce
) and execute it in Scilab:
This will display the sorted list of fruits and people.