Recursion in Scilab

Our example demonstrates recursion in Scilab. Here’s the full source code:

function result = fact(n)
    if n == 0 then
        result = 1;
    else
        result = n * fact(n-1);
    end
endfunction

disp(fact(7));

function result = fib(n)
    if n < 2 then
        result = n;
    else
        result = fib(n-1) + fib(n-2);
    end
endfunction

disp(fib(7));

This fact function calls itself until it reaches the base case of fact(0).

In Scilab, we define functions using the function keyword, followed by the output variable, the function name, and its parameters. The function body is enclosed between the function definition and endfunction.

The main execution in Scilab doesn’t require a specific function. We can simply write the code we want to execute in the script.

Scilab doesn’t have the concept of closures in the same way as some other languages. However, we can still define our recursive Fibonacci function as a regular function.

To run the program, save it as recursion.sce and use the Scilab console or GUI to execute it:

--> exec('recursion.sce', -1)
  5040.  
  13.  

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

Scilab doesn’t have a direct equivalent to Go’s closure recursion, but the concept of recursion remains the same. Functions can call themselves, and this is demonstrated in both the factorial and Fibonacci examples.