Session 11: Writing Scilab Functions [June 9, 2011, 1:52 p.m.]
Objectives
In this session you will learn the following:
- Writing inline functions
- Number of input and output arguments and default input arguments
Introduction
In session 10, we saw the basic skeleton for a Scilab function and a simple example to illustrate how to develop and use a function. Here we will take a closer look at counting input and output arguments. We will also see how do define an inline function.
Inline Functions
An inline function is a short function that can be defined without having to use the function skeleton discussed in Session 10. This is useful only when the body of the function is short (in case the body of the function is long, it could be first stored in a string and then used to define the inline function). We will again use the same function used in Session 10 as an example. The syntax for defining an inline function is:
deff(func_interface_str, func_body_str)
where func_interface_str is a string containing the interface of the function and func_body_str is a string containing the body of the function. The function to find the length of a line segment in 3D space can therefore be written as:
-->deff('[L] = len(p1, p2)', 'L = sqrt(sum((p2 - p1).^2))');
Alternately, the function could also be defined as:
-->s1 = '[L] = len(p1, p2)';
-->s2 = 'L = sqrt(sum((p2 - p1).^2))'
-->deff(s1, s2)
This could be advantageous when the body of the function contains many statements and is difficult to fit them all on a single line.
Number of Arguments
The number of input and output arguments are defined when the function is defined. However, it is possible to call the function without the correct number of matching parameters. Scilab therefore provides the function argn() to count the number of unput and output arguments at run time. Let us use the following function to show how this can be used:
function [a, b] = testarg(x, y, z)
[out, inp] = argn(0);
mprintf("Output: %d, Input = %d\n") // print function similar to printf in C
if inp == 1 then, y = 10, z = 20, end
if inp == 2 then, z = 20, end
disp([ x, y, z]);
a = x + y; b = 2 * z;
endfunction
Save this function in a file and load it into Scilab workspace. Let us call this function in the following different ways.
-->[a, b] = testarg(1, 2, 3)
Output: 2, Input: 3
b =
6.
a =
3.
-->[a, b] = testarg(1, 2)