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.
// Define a list of fruits
fruits = ["peach", "banana", "kiwi"];
// Define a comparison function for string lengths
function res = lenCmp(a, b)
res = length(a) - length(b);
endfunction
// Sort fruits by length using the gsort function with a custom comparison function
[sorted_fruits, perm] = gsort(fruits, "g", lenCmp);
disp(sorted_fruits);
// Define a structure for Person
Person = struct("name", "", "age", 0);
// Create a list of Person structures
people(1) = struct("name", "Jax", "age", 37);
people(2) = struct("name", "TJ", "age", 25);
people(3) = struct("name", "Alex", "age", 72);
// Define a comparison function for Person structures based on age
function res = ageCmp(a, b)
res = a.age - b.age;
endfunction
// Sort people by age using the gsort function with a custom comparison function
[sorted_people, perm] = gsort(people, "g", ageCmp);
// Display the sorted list of people
for i = 1:length(sorted_people)
disp(sprintf("%s: %d", sorted_people(i).name, sorted_people(i).age));
end
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:
$ scilab -f custom_sort.sce
This will display the sorted list of fruits and people.