6.3 Functions: Chapter 6 Functions and Loops
6.3 Functions: Chapter 6 Functions and Loops
Loops
6.3 Functions
A function is a set of codes that can be called when required. As a result,
it can be defined separately either its own file or within the body of the
program. A script file is similar in nature. A script file stores a sequence
of commands to be executed. It seems that a function and a script have a
similar nature, but, unlike MATLAB and Octave, Scilab provides separate
kinds of files for each one of them. This is based on the nature of their
behavior with the core Scilab program.
Whereas a script file (with extension .sce) is an executable file,
a function file (with extension .sci) stores a set of instructions. The
function file behaves like a black box where input is fed and output is
obtained. On the other hand, a script file changes its behavior as per input
values. Whatever input data a script file accesses is taken from the Scilab
workspace. Output data from a script file is put into the Scilab workspace.
The semantics of input data, local variables, are visible only within the
function.
The definition of a function follows this syntax:
152
Chapter 6 Functions and Loops
the function are mentioned. The last statement, endfunction, signifies the
end of the function.
For example, we can write a function to find x2 − y2 and assign it to
variable name z, as shown in Listing 6-5.
1 function y = fn1(a,b)
2 y = aˆ2−bˆ2;
3 endfunction
Notice that the extension of this code is .sci. This file must first be
loaded in a Scilab workspace. We need to provide the full path of the file to
the built-in function exec()first and then use the function by providing its
name with input arguments:
1 −−−>exec('/Users/sandeepnagar/.../fn1.sci', −1)
2 −−−>fn1(2,3)
3 ans =
4 −5.
1 function[y1,y2,y3] = fn2(x,y)
2 y1 = x − y;
3 y2 = x + y;
4 y3 = y − x;
5 endfunction
153
Chapter 6 Functions and Loops
1 −−−>exec('/Users/sandeepnagar/.../fn2.sci', −1)
2 −−−>[a,b,c] = fn2(2,3)
3 c =
4 1.
5 b =
6 5.
7 a =
8 −1.
1 −−−>exec('/Users/sandeepnagar/.../factorial1.sci', −1)
2 −−−>factorial1(10)
3 ans =
4 3628800.
154
Chapter 6 Functions and Loops
5 −−−>factorial1(10e5)
6 ans =
7 Inf
1 −−−>deff('[x] = mult(y,z)','x=y∗z')
2 −−−>mult(2,3)
3 ans =
4 6
6.4 Summary
Defining functions is the key to modular programming. Scilab presents an
elegant way to define and use functions both inline and in separate files.
When combined with the ability to write functions inside a loop, complex
problems can be implemented in a few lines of codes. It requires an artistic
attitude while designing an algorithm where functions and loops are the
paintbrush to devise an elegant solution to a given numerical problem.
155