Functions in Scilab

Functions are central in Scilab. We’ll learn about functions with a few different examples.

// Here's a function that takes two numbers and returns their sum
function result = plus(a, b)
    result = a + b
endfunction

// In Scilab, you can define multiple outputs for a function
function [sum, product] = plusAndMultiply(a, b, c)
    sum = a + b + c
    product = a * b * c
endfunction

// Main execution
// Call a function as you'd expect, with name(args)
res = plus(1, 2)
disp("1+2 = " + string(res))

[sum, prod] = plusAndMultiply(1, 2, 3)
disp("1+2+3 = " + string(sum))
disp("1*2*3 = " + string(prod))

To run this Scilab script, save it to a file (e.g., functions.sce) and execute it in Scilab:

--> exec('functions.sce', -1)
1+2 = 3
1+2+3 = 6
1*2*3 = 6

In Scilab, functions are defined using the function keyword, followed by the output parameter(s), the function name, and input parameters. The function body is enclosed between the function declaration and endfunction.

Unlike some other languages, Scilab doesn’t require explicit return statements. The last evaluated expression or the explicitly assigned output variables are automatically returned.

Scilab allows multiple return values from a function, as demonstrated in the plusAndMultiply function. This is similar to some other scientific computing languages but differs from languages that only allow a single return value.

When calling functions in Scilab, you use parentheses for the arguments, similar to many other programming languages.

Scilab is dynamically typed, so you don’t need to declare variable types explicitly. This differs from statically typed languages where you might need to specify the types of function parameters and return values.

There are several other features to Scilab functions, including optional arguments, variable number of arguments, and nested functions, which we’ll explore in future examples.