Programming With Scilab
Programming With Scilab
Module contents
B.1 Introduction . . . . . . . . . . . . . . . . . . . . 226
B.2 Getting started with Scilab . . . . . . . . . . . 227
B.3 Variables . . . . . . . . . . . . . . . . . . . . . . . 229
B.4 Arithmetic expressions . . . . . . . . . . . . . . 232
B.4.1 Precedence . . . . . . . . . . . . . . . . . . . . 232
B.4.2 Matrix arithmetic . . . . . . . . . . . . . . . . 233
B.4.3 Array arithmetic . . . . . . . . . . . . . . . . . 235
B.5 Builtin functions . . . . . . . . . . . . . . . . . 237
B.5.1 Arithmetic functions . . . . . . . . . . . . . . . 237
B.5.2 Utility functions . . . . . . . . . . . . . . . . . 240
B.6 Visualising data in Scilab . . . . . . . . . . . . . 241
B.6.1 Plotting mathematical functions from within
Scilab . . . . . . . . . . . . . . . . . . . . . . 241
B.6.2 Adding titles,labels and legends to the plot . . 244
B.6.3 Plotting numeric data stored in an ASCII le . 247
B.7 Script les . . . . . . . . . . . . . . . . . . . . . . 248
B.7.1 Script input and output . . . . . . . . . . . . . 250
B.7.2 Formatting script les . . . . . . . . . . . . . . 257
B.8 Function les . . . . . . . . . . . . . . . . . . . . 260
B.8.1 Local variables . . . . . . . . . . . . . . . . . . 265
B.9 Control structures . . . . . . . . . . . . . . . . . 265
B.9.1 Relational operations . . . . . . . . . . . . . . . 266
B.9.2 Logical operations . . . . . . . . . . . . . . . . 267
B.9.3 Branch controls (conditional statements) . . . . 269
B.9.4 Iteration controls (explicit loops) . . . . . . . . 273
B.9.5 Implicit loops . . . . . . . . . . . . . . . . . . . 278
B.9.6 Using functions and scripts together . . . . . . 279
B.10 Numerical programming . . . . . . . . . . . . . 280
B.10.1 Modular Programs . . . . . . . . . . . . . . . . 280
B.10.2 Debugging . . . . . . . . . . . . . . . . . . . . . 281
This module will lead you through numerical programming using
Scilab. When studying this module
1
, peruse all of the appendix
rst so that you have some idea of what can be found in it should
you need it in the course of writing programs for the other modules.
1
Everything in this module will be required when implementing the numerical
methods discussed in the rest of the course. Use this module as a reference
throughout the rest of the course.
225
226 Appendix B Programming with Scilab
Then, in conjunction with the numerical modules in the Study
Book you should refer to this appendix repeatedly as you attempt
the programming exercises throughout the course. This way your
programming skills will build up through writing programs. You
cannot learn how to write programs through reading alone any
more than you can learn how to drive a car from a manual.
B.1 Introduction
Scilab is an interactive programming environment. It allows the
user to interact directly with the Scilab interpreter through a
command window. Commands typed in at the command window
are executed immediately. Coupled with the rich graphical capa-
bilities of Scilab, the immediacy of the command window makes
it a good tool for data visualisation and investigating ideas and
concepts.
Using Scilab for numerical methods requires you to develop skill
in writing functions to perform various algorithms. Not only must
you have it clear in your mind what has to be done (the algorithm)
but you also need to analyse carefully which of the tasks will be
useful stand-alone tools.
Functions are used repeatedly in their area of application, either to
supply answers to well dened problems or to build other functions
to answer work specic problems. The important thing about a
function is that, having identied a well known task, what data
are required to complete the task and a way (or algorithm) for
completing the task, all this information is stored away and can be
recalled at will. If written carefully, functions are reusable across
projects and problems.
The skill of writing an eective function cannot be acquired by
just reading text like this module. To develop skills in writing nu-
merical programs, requires more than reading, it requires you to
write programs and to learn from the experience of writing pro-
grams. We recommend that this module be used as a reference
throughout the course. Everything in this module will be required
when implementing the numerical methods discussed in the course.
Your skill as a Scilab programmer should develop as the course
progresses and you are called on to write more complex programs.
As you write and use functions you will begin to appreciate the
features that make a particular function useful and what features
limit a functions usefulness.
When data is to be collected from the console or le, there should
be special functions designed to do just that jobthey may present
on-screen menus, boxes to be lled in, icons to be clicked on and so
forth. Designing a user interface is a whole area of study in itself.
Scilab does provide some interface tools which lead to quite a
B.2 Getting started with Scilab 227
professional looking product but it would take us the whole course
to master these and for the most part we will leave this activity to
other courses. Ours will be a study of ecient numerical techniques
and display of results will be plain and simple: that is why this
course is called High Performance Numerical Computing.
B.2 Getting started with Scilab
Starting Scilab will give a command window similar to the one
shown in Figure B.1. Commands are entered at the cursor (-->).
Each command is executed when either the return or enter key is
pressed. Any command execution can to be interrupted by pressing interrupt a running command
Ctrl & C keys together. To exit Scilab simply type exit or
quit at the command prompt
2
. Earlier commands executed in quit,exit
a session can be recalled using the up ()/down () keys on the
keyboard. Once recalled the command can either be edited using
the keyboard or re-executed by pressing the return/enter key. It
is also possible to combine multiple commands on the one command
line, by separating the commands using either a comma (,) or a
semi-colon (;). The semi-colon (;) suppress any output from the suppressing output from a
command
command being executed.
Figure B.1: The default Scilab Command Window
Help about commands and functions can be obtained by typing
help at the command plot. This will bring up a window where you help
2
Note as with all commands in Scilab this will not be executed until either
the return or entry is pressed
228 Appendix B Programming with Scilab
can search for help on version topics. Note you can short-cut this
window if you know the name of the command or function for which
you require help by typing help command or function name at
the command prompt. For example, to get help on the log func-
tion you would simply type help log at the command prompt.
In Scilab it is also possible to search for commands and/or func-
tions which contain certain keywords using the apropos command. apropos
As example, the command apropos(logarithm) will list all the
commands in Scilab relating to logarithms.
Example B.1: Sample commands in Scilab.
-->3^2-5-6/3*2
ans =
0.
-->3^2-5-6/(3*2)
ans =
3.
-->4*2^2+1
ans =
17.
-->sin(%pi/2)
ans =
1.
-->sqrt(25)
ans =
5.
-->sqrt(-4)
ans =
2.i
-->a1=5,b1=3,c1=sqrt(a1+b1)
a1 =
5.
b1 =
3.
c1 =
2.8284271
-->ans
ans =
2.i
-->t=linspace(0,%pi/2,6)
t =
0. 0.3141593 0.6283185 0.9424778 1.2566371 1.5707963
-->y=cos(t)
y =
1. 0.9510565 0.8090170 0.5877853 0.3090170 6.123D-17
Example B.1 illustrates an important feature of the Scilab com-
putational engine. If an expression is just typed in and evaluated
the answer is stored in a special variable called ans. This vari- ans
B.3 Variables 229
able contains the value of last unassigned (see B.3 for details on
how variables are assigned) evaluation performed. Hence, the value
stored in ans changes each time an unassigned calculation is per-
formed in Scilab as illustrated in Example B.1. Consequently,
if you intend to reuse values of calculations you should store the
results in a variable (see B.3) to avoid the possible of using the
incorrect result.
Activity B.A To familiarise yourself with some of the basic features of !
Scilab and how to use it for elementary arithmetic and
as a sophisticated calculator try some of the examples in
Example B.1. Make sure you understand what Scilab
did to calculate the answer. Also as you work through
the appendix attempt all the examples and exercises as
you come to them.
B.3 Variables
Variables are used in a programming language as tags to memory
locations in the computer. The data stored in the memory location
is accessed using the variable name in the program. The variable
is not attached to the data but the memory location. This means
that the value contained within a variable can change.
In languages such as C every variable must be declared before it is
used, specifying both its name and its type. The name and type of
variables do not need to be pre-declared in Scilab. In Scilab any
variable can take integer, real, complex, scalar, string, or matrix
values. Languages that pre-declare variables have clearly stated
at the start of a program or function the type of every variable
used. The Scilab interpreters liberal approach to variable types
has both advantages and disadvantages.
The equality sign (=) is used to assign the values to a variable. assigning values to
variables
This is an unfortunate choice of symbol and means that when we
want to test whether two quantities are equal or not, we cannot use
the equal symbol, =, but must use the more cumbersome ==. Thus
5+2 == 3+4 is true but 5+2 = 3+4 is a syntax error. In Scilab
programs, the equals sign does not have its mathematical meaning.
It is an assignment operator. The statement to the right of the
equals sign is evaluated and the result is placed in the memory
location tagged by the variable name on the left. For example, the
statement x = 3 + 5 means Scilab evaluates the statement on
the right and stores the result in the memory location tagged by
the variable x. This means that the statement 3+ 5 = x, which
is equivalent to x= 3 + 5 in mathematics, will lead to an error
message in Scilab.
The following are examples of variable types in Scilab (it is not
complete but contains all the variable types that you will encounter
230 Appendix B Programming with Scilab
in this course).
x = 3; Assign the scalar integer value 3 to the variable x.
x = 7.297e17; Assign the scalar real value 7.297 10
17
to the variable x.
The number has been dened using the scientic exponent
notation. The number following the e is the power of 10 to
multiply the number in front of the e. Either e or E can be
used.
x = North; Assign the string North to the variable x. Strings of char-
acters are dened by surrounding the characters with apos-
trophes. The construct South denes a constant string
containing the characters South.
x = 0:5:100; Assign the row vector containing 21 elements from 0 to 100
in steps of 5 to the variable x.
x = [1.2 1.3; 2.5 6.7]; Assign the 2 2 matrix to the variable x, so that
x =
1.2 1.3
2.5 6.7
1.
%inf This is Scilabs representation of . This is a
recognised value in a variable and typically ap-
pears as a result of division by zero, or logarithm
of zero
%nan Stands for Not a Number. This is a recognised
value in a variable and appears as a result of
a mathematically undened operation, such as,
division of zero by zero, or .
%eps Floating point relative accuracy. That is, %eps
returns the smallest dierence resolvable be-
tween two oating point numbers. For example,
the next largest representable number beyond
1.0 is 1.0+%eps . Scilab cannot represent any
oating point number that falls between 1.0 and
1.0+%eps .
ans This variable contains the last computed expres-
sion that was not stored in a variable.
date This variable contains a string representation of
todays date, in the format dd-mmm-yyyy. For
example, 01-Apr-2000
232 Appendix B Programming with Scilab
Table B.2: Scilab Arithmetic Operators
Operator Meaning Scilab
^ Exponentiation: x
y
x^y
* Multiply: x y x*y
/ Right Division : x/y =
x
y
x/y
\ Left Division: y\x =
x
y
y\x
+ Addition: x + y x+y
- Subtraction: x y x-y
of a calculation will be stored in a special variable called ans (see ans
Table B.1). The value stored in this variable is overridden the next
time a calculation is done that is not assigned to a variable. This
means that the result from the previous calculation is then lost.
B.4 Arithmetic expressions
Table B.2 lists the basic arithmetic operators to be found in Scilab.
With the exception of the left division operator, the arithmetic op-
erators in Scilab follow standard notation.
B.4.1 Precedence
When more than one operation appears in a mathematical state-
ment, the programming language needs to dene in which order the
operations must be performed, or the precedence. That is, which
parts are evaluated rst.
If precedence was not dened then the same statement can be eval-
uated to a dierent result: for example, is 18/6+3 equal to 2? or
is 18/6+3 equal to 6? The rst statement is evaluated from the
right using the precedence rule that usually applies in mathemat-
ical statements: that is, work from right to left, as for example in
sin log tan x where we start with a value of x, compute the tan-
gent of that value (tan x) then take the logarithm of the resulting
number (log(tan x)) and nally take the sine of what this deliv-
ers. However, it is usual (because it is much easier to write poly-
nomials with this convention) to give multiplication and division
precedence over addition and subtraction. The second statement
recognises the precedence of the division over addition and evalu-
ates it rst. Right to left precedence has a much simpler parsing
tree than schemes which give precedence to particular operators,
but the common arithmetic precedences are so widely accepted
and expected that most computer language designers will not risk
the possible consumer backlash that breaking with this tradition
would involve. So with every computer language one must search
out and learn the precedence rules that it adopts. The usual arith-
metic precedences will normally be observed, but note that even
B.4 Arithmetic expressions 233
Table B.3: Precedence of arithmetic expressions
Operator Precedence Order of evaluation
() 1 Left to right, innermost rst
\ 2 Left to right
* / 3 Left to right
\ 4 Right to left
+ 5 Left to right
they are not unambiguous. For example, which divide has prece-
dence in 4/16/32 ? Working right to left, one would get the answer
of 8, but Scilab returns (the decimal for) 1/128 it works from
left to right. Table B.3 lists the operators and their precedence
value.
The rules for evaluation of operators are as follows
Operators having high precedence (low numerical value) will
be evaluated before those having a low precedence (high nu-
merical value).
If an expression contains more than one operator at the same
level of precedence, then the left-to-right rule of evaluation
apply.
Parentheses (...) always have the highest precedence. Whatever
is within the parentheses is evaluated rst. This means, when in
doubt about the order of any statement place parentheses around
the statement to ensure that the operations are performed in the
order you expect.
B.4.2 Matrix arithmetic
One of the strengths of Scilab is its ability to execute matrix
arithmetic
3
. Matrix arithmetic must be implemented in other lan-
guages with many lines of code or special functions. Scilab is
especially designed to handle matrix arithmetic. The * represents
matrix multiplication or scalar multiplication of a matrix if one of
the arguments is a scalar. Since scalars are 11 matrices ordinary
scalar multiplication can also be performed by the * operator. The
dot product of two vectors, however requires that the rst vector
be a row vector and the second a column vector. To multiply the
corresponding elements in two vectors together requires a dierent
operator .* so that
> a = [2 3 4] ; b = [6, 7, 8];
a .* b
ans =
12. 21. 32.
3
Remember, vectors are examples of matrices. A column vector of length n
is an example of a n 1 matrix.
234 Appendix B Programming with Scilab
However, because it is a matrix operation
> a + b
ans =
8. 10. 40.
The standard arithmetic operators described in Table B.2 are also
used with matrices. The normal rules of matrix addition, subtrac-
tion, and multiplication apply.
The left and right division of matrices are also generalisations of
scalar division. Right division B/A is roughly the same as B*inv(A).
Left division A\B is roughly the same as inv(A)*B. The dierence
is in how the division is performed. Dierent algorithms are used
when A or B are square or not.
Scilab also denes a transpose operator for matrices. The trans-
pose of the matrix A is A. For example, if
A =
2.5 6.3
1.2 0.9
, then A
2.5 1.2
6.3 0.9
.
Accessing matrix elements
Individual elements of a matrix can accessed and used in state-
ments by specifying the matrix index of an element. The index of
an element is its position in the matrix. For example, consider the
following matrix
A =
6 1 4
3 5 7
3 6 1
x
2
+ y
2
)/
x
2
+ y
2
illustrating the
3d capabilities of Scilab.
B.6 Visualising data in Scilab
One of the big advantages in using Scilab is the ability to visualise
data and results of complex calculations (see Figure B.2 as example
of the 3d capabilities). While Scilab is capability of complex 3d
graphics (see help pages for mesh and surf) in this section we will mesh & surf
focus on the 2d plotting command (plot). Hence, in this section plot
we will focus on:
1. plotting mathematical functions from within Scilab;
2. changing stylistic elements of the plot;
3. adding titles, labels and legends to the plot;
4. including mathematical notation in titles, labels and legends;
and
5. plotting data stored in an external ASCII le.
B.6.1 Plotting mathematical functions from within Scilab
To plot a mathematical function in Scilab three steps are required.
These are:
1. Dene the domain of the function (e.g. x=linspace(0,2*%pi))
2. Calculate the values of function at the selected points in the
domain (e.g. y=sin(x))
242 Appendix B Programming with Scilab
3. Final step is to plot the function using the plot command plot
(e.g. plot(x,y)).
Using these steps it is possible to produce a basic plot of any math-
ematical function (see Figure B.3). Note that the plot shown in
Figure B.3 does not have a title, axes labels or a legend, all of
which are crucial for a good plot. The Scilab commands to add
these elements to the plot are given in the following sections.
- 1.0
- 0.8
- 0.6
- 0.4
- 0.2
0.0
0.2
0.4
0.6
0.8
1.0
0 1 2 3 4 5 6 7
Figure B.3: The default plot of y = sin(x) in Scilab. Note
that by default axes are not labelled, and there is no title or
legend. These need to added using the additional commands
xlabel,ylabel,title and legend.
Changing stylistic elements of the plot
An optional argument can be given to the plot command to cus-
tomise each new line aspect. This argument is a concatenated
string containing information about colour, line style or markers
based on the speciers shown in Table B.8. To specify the plot
be drawn with a red longdash-dot line with diamond marker, the
string that would be passed to plot command would be r-.d. The
string, which is a concatenation (in any order) of the three types
of properties shown in Table B.8, must be unambiguous. Further-
more, the string specication is not case sensitive. An example
of specifying various line styles is shown in Example B.6 and Fig-
ure B.4.
Example B.6: The following commands illustrate how line styles
can be used to distinguish between the plots of sin(2t), sin(2t+
/6), and sin(2t + /2).
t=linspace(0,1,30)
B.6 Visualising data in Scilab 243
Table B.8: Plot speciers required to change line styles, colours
and markers in plots
Specier Line style Specier Colour Specier Marker style
Solid line (default) r Red + Plus sign
Dashed line g Green o Circle
: Dotted line b Blue * Asterisk
. Dash-dotted line c Cyan x Cross
m Magenta s Square
y Yellow none No marker(default)
k Black
w White
y2=sin(2*%pi*t+%pi/2)
y1=sin(2*%pi*t+%pi/6)
y=sin(2*%pi*t)
mtlb_hold on
plot(t,y,r-o,LineWidth,1.5)
plot(t,y1,g-.s,LineWidth,1.5)
plot(t,y2,c--d,LineWidth,1.5)
legend($y=\sin(2\pi{t})$,$y=\sin(2\pi{t}+\pi/6$),...
$y=\sin(2\pi{t}+\pi/2)$)
legend($y=\sin(2\pi{t})$,$y=\sin(2\pi{t}+\pi/6)$,...
$y=\sin(2\pi{t}+\pi/2)$)
xlabel(t)
ylabel(y)
- 1.0
- 0.8
- 0.6
- 0.4
- 0.2
0.0
0.2
0.4
0.6
0.8
1.0
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
t
y
Figure B.4: Resulting plotting after issuing the commands given
in Example B.6.
244 Appendix B Programming with Scilab
Example B.6 illustrate a number of key commands relating to the
creation of multiple plots in Scilab. The mtlb hold
4
command mtlb hold
holds the current plot and axis properties so that all subsequent
plots are added to the existing plot.
To distinguish each plot, a dierent line specication is passed each
plot command. In the example, y = sin(2t) is plotted using a red
solid line with data points indicated using a red circle, as indicated
by the string r-o; y = sin(2t + /6) is plotted using green
dashed-dotted line with data points marked by a square (g-.s);
while y = sin(2t +/2) is plotted using a cyan dashed line using
diamonds to mark the data points (c--d). Finally, to complete
the plot axes labels and a legend has been added to plot, the com-
mands for doing this are discussed in B.6.2.
B.6.2 Adding titles,labels and legends to the plot
All good plots should have the following properties:
1. The style of gure is appropriate to the information being
conveyed;
2. The contents are well organised, so it is easy for readers to
interpret the information;
3. Legends, labels etc. are clear and concise (e.g. contain units
if required, do not obstruct parts of the plot etc.); and
4. A caption or title that summarises the information presented.
Like most mathematical applications Scilab has a wide variety of
dierent plotting styles that can be used (e.g. look up the help for
bar, polarplot etc.). This allows you to select the most appropri- bar,polarplot
ate style to display and organise your data.
The Scilab commands xlabel, ylabel, title and legend al- xlabel, ylabel, title, and
legend
lows you to add axes labels, titles and legends to plot. As shown
in Example B.6 the commands xlabel, ylabel, and title take
a string input containing the title or label text. For the legend
command, a string is required for each separate plot. Note the
order of the strings in the legend command reects the order in
which the each of plots were made.
Including mathematical notation in titles, labels and legends
It is possible to include mathematical characters such as in
Scilab plots. This is done by inserting special commands into
either the title, legend or label string. These commands are based
on the abbreviations for mathematical notation used in programs
such as L
A
T
E
X, MathType etc. A brief summary of the commands
4
mtlb hold on is equivalent to the Scilab command
set(gca(),"auto clear","off"), while mtlb hold off is equivalent
to the Scilab command set(gca(),"auto clear","on")
B.6 Visualising data in Scilab 245
Table B.9: Basic mathematical symbols available in Scilab for
including mathematical notation in titles, labels and legends.
command symbol command symbol command symbol
\alpha \upsilon \sim
\angle
\phi \leq
\ast \chi \infty
\beta \psi \clubsuit
\gamma \omega \diamondsuit
\delta \Gamma \heartsuit
\epsilon \Delta \spadesuit
\zeta \Theta \leftrightarrow
\eta \Lambda \leftarrow
\theta \Xi \Leftarrow
\vartheta \Pi \uparrow
\iota \Sigma \rightarrow
\kappa \Upsilon \Rightarrow
\lambda \Phi \downarrow
\mu \Psi \circ
\nu \Omega \pm
\xi \forall \geq
\pi \exists \propto
\rho \ni \partial
\sigma \cong
= \bullet
\varsigma \approx \div
\tau \Re \neq ,=
\equiv \oplus \aleph
\Im \cup \wp
\otimes \subseteq \oslash
\cap \in \supseteq
\supset \lceil , \subset
\int
\cdot \o
\rfloor | \neg ,= \nabla
\lfloor \times \ldots . . .
\perp \surd
\prime /
\wedge \varpi \O
\rceil | \rangle \mid |
\vee \copyright c _ \langle
available in Scilab for typesetting mathematical notation is given
in Table B.9. To insert these commands into a text string, simply
start and end the string with $ signs, as shown in Example B.7.
Example B.7: Scilab commands to produce the labelled plot of
y = sin
2t +
4
2t +
4
C)
0.0000 100.0000 51.0000 22.9759
1.0000 95.0000 52.0000 22.7900
2.0000 90.3125 53.0000 22.6156
3.0000 85.9180 54.0000 22.4521
4.0000 81.7981 55.0000 22.2988
5.0000 77.9357 56.0000 22.1552
6.0000 74.3147 57.0000 22.0205
7.0000 70.9201 58.0000 21.8942
8.0000 67.7376 59.0000 21.7758
9.0000 64.7540 60.0000 21.6648
10.0000 61.9568 61.0000 21.5608
11.0000 59.3345 62.0000 21.4632
12.0000 56.8761 63.0000 21.3718
13.0000 54.5714 64.0000 21.2860
14.0000 52.4107 65.0000 21.2057
15.0000 50.3850 66.0000 21.1303
16.0000 48.4859 67.0000 21.0597
17.0000 46.7056 68.0000 20.9934
18.0000 45.0365 69.0000 20.9313
19.0000 43.4717 70.0000 20.8731
20.0000 42.0047 71.0000 20.8186
21.0000 40.6294 72.0000 20.7674
22.0000 39.3401 73.0000 20.7194
23.0000 38.1313 74.0000 20.6745
24.0000 36.9981 75.0000 20.6323
25.0000 35.9357 76.0000 20.5928
26.0000 34.9397 77.0000 20.5557
27.0000 34.0060 78.0000 20.5210
28.0000 33.1306 79.0000 20.4885
29.0000 32.3100 80.0000 20.4579
30.0000 31.5406 81.0000 20.4293
31.0000 30.8193 82.0000 20.4025
32.0000 30.1431 83.0000 20.3773
33.0000 29.5092 84.0000 20.3537
34.0000 28.9148 85.0000 20.3316
35.0000 28.3577 86.0000 20.3109
36.0000 27.8353 87.0000 20.2915
37.0000 27.3456 88.0000 20.2733
38.0000 26.8865 89.0000 20.2562
39.0000 26.4561 90.0000 20.2402
40.0000 26.0526 91.0000 20.2252
41.0000 25.6743 92.0000 20.2111
42.0000 25.3197 93.0000 20.1979
43.0000 24.9872 94.0000 20.1855
44.0000 24.6755 95.0000 20.1739
45.0000 24.3833 96.0000 20.1631
46.0000 24.1093 97.0000 20.1529
47.0000 23.8525 98.0000 20.1433
48.0000 23.6117 99.0000 20.1344
49.0000 23.3860 100.0000 20.1260
50.0000 23.1743
250 Appendix B Programming with Scilab
A script le is a le of standard keyboard characters
that dene commands to drive a program. A script le
can be generated using any text editor or word proces-
sor.
To invoke a script in Scilab, type the command exec
exec "filename.sce";
where filename denotes the actual name of the le containing the
script. When the script runs it is exactly the same as if you typed
the commands into the command window from the keyboard. This
means that the Sci-le can use any variables you have dened prior
to invoking the script. Any variables created in the script are also
available when the script is nished and any variable whose name
was assigned a value in the script will be over-written.
If you give a script the same name as any variable that it computes
in the running of the script, then Scilab will give precedence to
the workspace variable over a script. As stated in B.3 the variable
name will hide the script name after the script has run. Scilab will
take the name as referring to the variable and not to the dened
script.
Scilab also needs to know where to nd the script to executed.
If Scilab cannot nd the script it will report that you have an
undened function or variable.
The exact procedure for creating and saving Sci-les depends on
the Scilab version, the operating system (MS Windows, Macin-
tosh, or Unix/Linux ), and the text editor you use. The current
version of Scilab includes a built-in editor which can be used to
create and edit Sci-les and text les.
To create a new Sci-le under the current version of Scilab simply
type edit newfilename.sce. This will open up the Scilab editor edit
with a blank document called newfilename.
B.7.1 Script input and output
A script is a named le (with the extension .sce) containing a
sequence of Scilab instructions which, when its name is executed
in a session performs those instructions in order as though they
were entered at the console.
There are two common uses for scripts. Pragmatically we may
want to save a particular computational sequence for later use or
reference. If the tasks involved are to be repeated often, then
the nature of the tasks should be analysed, formulated into useful
functions (which we will discuss later) and the whole procedure
presented in a single function. But, if the tasks are only likely to
get occasional use, then the script may be adequately commented
and stored as a script le. It is a quick and dirty way of saving
B.7 Script les 251
the instructions for doing a particular job, when we do not want
to go to the trouble of writing the functions for the job. It is not
a highly recommended modus operandi, but useful all the same.
The second use is for the script to act like a storyboard presenting
information to a user in a structured and controlled way permit-
ting the user to see the steps of a computational procedure and
their outputs up on the screen. At a more sophisticated level, the
script takes on the proportions of an application controlling a large
and complex interaction with advanced interface features. We will
not take our study of Scilab programming to this level, but work
mostly at the storyboard level using the simplest of Scilabs in-
terface tools.
All the variables created in a script become global variables dened
in the workspace and available for perusal. As an application it
is assumed that a script controls the entire workspace and the
variables it creates are the data of the application. When scripts
are used as storyboards on a small scale then it cannot be assumed
that the variables they create deserve global recognition and it is
courteous to erase these variables when the script is nished unless
they have some possible further use. An unfortunate side-eect is
that if variables with the same name already exist in the workspace
before a script is run then these variables will be over-written and
lost.
Used as storyboards, scripts allow the user to cut, paste and re-try
the various steps of a procedure and to modify the script to suit
his own needs. Storyboards may be used for demonstrations of
toolbox utilities or extended documentation/explanation of func-
tions. However, if there is any danger that variables dened by
the script may over-write workspace variables then the demo or
documentation should be re-fashioned into a function that leaves
the workspace variables untouched (more on this later).
Scripts will often read data from pre-prepared les and we will dis-
cuss the functions provided by Scilab to perform this task below.
Gathering data entered by the user really falls into the realm of
interface design but we only briey consider the simplest interface
function provided by Scilab. Similarly, we briey consider the
functions for providing the simplest forms of output presentation.
Keyboard input
Scilab has a built-in function input that can be used to prompt input
the user to enter the value of a variable from the keyboard. For
example,
Tc = input(Please enter the temperature in degrees Celsius:);
will print the message
252 Appendix B Programming with Scilab
Please enter the temperature in degrees Celsius:
and Scilab will wait for the input. The input is terminated by
pressing the Enter (or Return) key.
The input entered can be any valid Scilab expression, which will
be evaluated, and the answer assigned to the variable (in this case
Tc) in the input statement. For example:
Please enter the temperature in degrees Celsius: [0:25:100]
where the [0:25:100] has been entered by the user in response to
the input prompt. The variable Tc will be assigned the row vector
[0, 25, 50, 75, 100].
Example B.8:
// Script : quad_0s
// Variables created/overwritten:
// A, B, C, D, x1, x2, x, y, a, b, w, thezeros
// Purpose: To illustrate the use of the
// quadratic formula for solving
// a quadratic equation of the form
// Ax^2 + Bx + C = 0
// with the user to enter A,B,C
// Source: Leigh Brookshaw, Mar 15, 2000;
// Last Modified: Tony Roberts, 2007
clc
disp([
**********************************
Calculating the solutions
of the equation Ax^2 + Bx + C = 0
**********************************
])
input(Press Enter to start);
A = input(Enter value of A in Ax^2+Bx+C: );
B = input(Enter value of B in Ax^2+Bx+C: );
C = input(Enter value of C in Ax^2+Bx+C: );
disp(First we compute the discriminant)
D = B^2 - 4*A.*C
input(Press Enter to continue);
// The quadratic formula gives:
x1 = (-B + sqrt(D))./(2*A);
x2 = (-B - sqrt(D))./(2*A);
thezeros=sort([x1,x2])
input(Press Enter to continue);
// Check this from a graph of the function.
B.7 Script les 253
if D<0
a=-B/(2*A); b=-B/(2*A); w=4*abs(a);
x1=a; x2=a;
else
a=min([x1,x2]); b=max([x1,x2]); w=b-a;
end
x=linspace((a-w/4),(b+w/4),100);
y=A*x.^2+B*x+C;
plot(x,y,x1,0,*,x2,0,*)
clear x y a b w
There are several things to note about this script.
(a) Echoing the instructions on the screen is turned o when
the input function is to be used and comments are
then put onto the screen with the disp function. This
method of displaying comments could be kept through-
out the script.
(b) The input function may be used to punctuate the pre-
sentation so that it does not all just scroll past the
viewer without his having the opportunity to read how
the computation progresses.
(c) The graphing of the function involves a few considera-
tions that we do not wish to trouble you with, since we
want you to concentrate of the quadratic formula. The
variables used in this part of the script are erased with
clearbut note that if any variable in the workspace
is called a, b, x, y or w then the result will be that it is
erased.
(d) If you write a similar script for solving say two equations
in two unknowns then you will see that most of the time
will be spent on perfecting the layout of the presentation
rather than on the solution process.
Formatted output
The semicolon at the end of a line in Scilab suppresses the display
of output from a computation, but allowing the output to be dis-
played in Scilabs default mode is sometimes not very convenient.
Scilab provides the function printf (a direct implementation of printf
the C function of nearly the same name) for formatted output. The
form the command takes is:
printf(format,A,B,...);
The string format describes how to display the variables A,B,.... format
The format string contains text to be displayed plus special com-
mands that describe how to display each number. The special
commands takes the general form
254 Appendix B Programming with Scilab
%[-][number1.number2]C
where anything in square brackets is optional.
The % sign tells Scilab to interpret the following characters as
codes for formatting a variable. The number1 species the mini-
mum eld width.
9
If the number to be printed will not t within
this width, then the eld will be expanded. The number2 species
the number of digits to print, to the right of the decimal point.
That is, the precision of the output. If the precision of the variable
is larger than the precision of the output eld, then the last digit is
rounded before printing. Normally the numbers printed are right
justied, the minus sign indicates that they should be left justied.
The nal character in the format specier C is the format code.
This is not optional, it must appear to specify what form the num-
ber is to be printed. Table B.12 lists the most useful format codes.
Example B.9: Some examples of using the printf command.
printf(The speed is (kph): %3.1f,Speed);
if Speed = 62.34 , this produces the output
The speed is (kph): 62.3
If A = 3.141, and B = 6.282 , then the command
printf(Pi=%5.3f, TwoPi=%5.3f,A,B);
produces the output
Pi=3.141, TwoPi=6.282
If M=[1.2 1.5; 0.6 0.3], then the command:
printf(%3.1f ,M);
produces the output
1.2 0.6 1.5 0.3
The printf command prints by column when a matrix is to
be printed.
Example B.10: An example of the rounding that can occur when
using printf. The output from the command
printf(Pi=%7.5f, Pi=%6.4f,pi,pi);
is
Pi=3.14159, Pi=3.1416
The format string can also contain ordinary text which will be out-
put unchanged. Escape sequences can be embedded in the format
9
this is the minimum number of characters the number will occupy, including
the decimal point and signs. For example the eld width of 2.345 is 6 .
B.7 Script les 255
Table B.12: The printf format string number types
Format code Description
%f Decimal format.
%e Exponential format with lowercase e
%E Exponential format with uppercase E
%g %e or %f, whichever is shorter
%G %E or %f, whichever is shorter
Table B.13: The printf format string escape sequences.
Escape Sequence Description
\n start a new line in the output
\b Backspace
\t Tab
\\ Print a backslash
%% Print a percent
Print an apostrophe
string that have special meaning. Table B.13 lists the most useful
escape sequences.
File input and output
Variables can be dened from information that has been stored
in a data le. Scilab recognizes two dierent type of data les:
mat-les and ascii-les. A mat-le contains data stored in a
space-ecient binary format. Only a Scilab program can read
mat-les. If data is to be shared with other programs, then use
the ascii le type. An ascii (American Standard Code for In-
formation Interchange) le contains only the standard keyboard
characters, and is readable and editable on any platform using any
text editor.
To save variables to a mat-le, use the command save. For exam-
ple:
save(data1.mat,x,y);
will save the matrices x and y in the le data1.mat. To restore
these matrices in a Scilab program, use the command
10
:
load(data1.mat);
This command will dene the variables x and y and load them with
the values stored in the mat-le. The advantage of saving data in
a mat-le is that when it is loaded the variables are restored. The
disadvantage is that the le is a binary le and is only readable by
Scilab.
10
Remember this le must be in the Scilab search path
256 Appendix B Programming with Scilab
An ascii data le that is going to be loaded into a Scilab program
must only contain numeric information, and each row of the le
must contain the same number of data values. The le can be
generated using a spread sheet program, a text editor, or by any
other program. It can also be generated by a Scilab program
using the fprintfMat command. To save the variable y to an
ascii le called data1.dat, the command is:
fprintfMat(data1.dat,y)
Each row of the matrix y will be written to a separate line in the
data le. The .mat extension is not added to an ascii le. How-
ever, it is good practice, as illustrated here, to add the extension
.dat to all ascii data les so that they can be distinguished from
other Scilab le types, and are easily recognisable as data les.
Exercise B.11: Use the Scilab help command to discover more
options for fprintfMat.
The fscanfMat command reads an ascii le of numbers. For ex-
ample:
x=fscanfMat(data1.dat)
assigns to variable x the matrix of values in the text les data1.dat.
Example B.12: If the le data3.dat contains the following data:
0.00 0.00
0.01 0.01255
0.02 0.2507
0.03 0.37815
The command:
data3=fscanfMat(data3.dat);
will create a variable data3 with 2 columns and 4 rows, that
will contain the data from the le. Then typing data3 at the
prompt will give
> data3=fscanfMat(data3.dat)
data3 =
0 0
0.0100 0.0126
0.0200 0.2507
0.0300 0.3781
Then the columns of data in the le can be stored in the vari-
ables x and y by simply doing the following: x=data3(:,1)
and y=data3(:,2).
Exercise B.13: Create the ascii data le xyz.dat containing the
following data
B.7 Script les 257
Table B.14: Some of Scilabs data input/output functions.
Function Description
input Request input from the keyboard. Any
valid Scilab expression is allowed in re-
ply.
disp Display variables in free format
fprintf Display/print variables in a specied for-
mat
save Save variables to a le
load Load data from a le
fscanfMat Load data from an ascii le.
fprinfMat Write ascii data to a le.
0.00 0.01 0.02 0.03
0.12 0.32 0.45 0.87
1.34 1.21 1.78 1.47
Use the Scilab editor or a text editor of your choice.
Load the data le into Scilab so that the three variables x,
y, and z each contain a row of data from the le.
Note that other more advanced commands exist in Scilab and
can be used to read/write ascii les (see Table B.14). However
these are only used when a specic need arises and are therefore
not covered in detail here (see Scilab Help for more details).
B.7.2 Formatting script les
An important aspect of writing script les is to ensure that the
script is readable and easily understood. This ensures that anyone
reading the script le (this includes the author of the le) can
understand the purpose of the script.
To help make the script understandable it should be commented
throughout describing all aspects of the script. In Scilab all text
on a line following two \\ characters is treated as a comment. The
rst comment line before any executable statement in a script is the
line that is searched by the apropos command. This line should apropos
contain the name of the function and keywords that help locate
the script. The help command displays all the comment lines, up
to the rst blank line or executable line, that occur at the start of
a script. A description of the script should be placed here
11
.
Lines in a script le should not be too long. The lines should be
11
Note help les will only be available online in Scilab once the required xml
help les have been generated. If you use the above structure these can be
generated from your Sci-le by running the command help from sci. For
additional details see Scilab help for this command.
258 Appendix B Programming with Scilab
visible in the editors window/(printout) without wrapping or hori-
zontal scrolling. This applies to both comment lines and statement
lines.
Statements can be broken across multiple lines using the continua-
tion symbol ..., three dots in a row. If three dots in a row appear Continuation symbol(...)
at the end of a line it means that the statement is continued on
the next line.
Example B.14 is an example of a script le that explains how to
make various temperature conversions.
Example B.14:
// Script : temperatures
// Variables created/overwritten:
// Tc, Tf, Tk, Tr T_all
// Purpose: To illustrate the conversion of
// Celsius temperatures (Tc) to
// Fahrenheit (Tf), Kelvin (Tk),
// and Rankine (Tr) and to produce
// a table of equivalents to Tc values
// running from 0 to 100 in steps of 10
// Source: Leigh Brookshaw, Mar 15, 2000;
// Last Modified: Tony Roberts, 2007
// -----------------------------------------------
disp(We create the list of Celsius values)
Tc = [0:10:100], input(pause);
disp(Calculate the Fahrenheit equivalents)
Tf = 9*Tc/5 + 32, input(pause);
disp(Calculate the Kelvin equivalents)
Tk = 273.16 + Tc, input(pause);
disp(Calculate the Rankine equivalents)
Tr = 9*Tk/5, input(pause);
disp(Create a matrix with equivalent temperatures)
disp(in corresponding rows:)
T_all = [Tc; Tf; Tk; Tr], input(pause);
// Turn echoing off as the rest is instructional
printf(Temperature Conversion Table\n);
printf( Tc Tf Tk Tr\n);
printf(%6.2f %6.2f %6.2f %6.2f\n,T_all);
// The print instruction works because printf
// prints a row at a time.
// \n starts a new line in the output
B.7 Script les 259
// As a courtesy clear out the
// introduced/over-written variables.
clear Tc Tf Tk Tr T_all
Exercise B.15: Code the Example B.14 and name the script le
temperatures.sce. Test that your script le is giving the
correct answers. Test the answers by calculating a few of
the values in the output table using the Scilab command
window.
Run your script with disp as shown, then comment out these
displays when you are satised the script works.
Exercise B.16: The growth of bacteria in a colony can be mod-
eled with the following exponential equation
y
new
= y
old
e
1.386 t
where y
old
is the initial number of bacteria in the colony,
y
new
is the new number of bacteria in the colony, and t is the
elapsed time in hours.
Write a script that uses this equation to predict the number
of bacteria in the colony after 6 hours if the initial population
is 1. Print a table that shows the number of bacteria every
half hour up to 6 hours. Also plot the answer.
Exercise B.17: Modify the script of Exercise B.16 so that the
user enters the elapsed time in hours. Use the input com-
mand to ask the user for the input.
Exercise B.18: Modify the script of Exercise B.17 so that the
user enters the initial population of the colony.
Exercise B.19: Carbon dating is a method for estimating the age
of organic substances, such as bones, wooden artifacts, shells,
and seeds. The technique compares the amount of carbon 14,
a radioactive isotope of carbon, contained in the object with
the amount it would have had when it was alive. While living
the object would have the same amount of carbon 14 as its
surrounding environment. For the last tens of thousands of
years the ratio of carbon 14 to ordinary carbon has remained
relatively constant in the atmosphere, this allows an estimate
to be made of age based on the amount of surviving carbon
14 in an object. The equation is
age(years) =
log
e
(carbon 14 proportion remaining)
0.0001216
If the proportion of carbon 14 remaining is 0.5, then the age
is 5700 years. Which as you would expect is approximately
the half life of Carbon 14.
260 Appendix B Programming with Scilab
Write a script that allows the user to enter the proportion of
carbon 14 remaining. Print the age in years.
What happens if the user enters a proportion 0? What
happens if the user enters a proportion 1?
Exercise B.20: Modify the script of Exercise B.19 so that the
age is rounded to the nearest year.
B.8 Function les
While a script is intended to be either the controlling unit for an
entire application or a storyboard for a minor application, the
computational work, the various specialised tasks that make up an
application are done through the use of functions. We have seen
numerous examples of functions alreadythe built-in or primi-
tive functions of Scilab such as input, floor, and ceil, the
arithmetic functions, +, -, *, /, ^ and elementary functions of
mathematics such as sin, cos, tan, exp, log. But in most appli-
cations, there are special tasks that recur and for which it would
be useful to have a function. Scilab permits the user to dene his
own functions and to store them in separate Sci-les called function
les.
Functions must have a particular syntax. Only pre-x notation is
allowed and the rst executable line of a function Sci-le must be
preceded by a line of the form
function [u,v,w] = Fname(x,y,z,t)
where Fname is the unique name of the function which requires one
or more (or no) inputs x,y,z,t and returns one of more (or no)
outputs u,v,w. The following lines of the function le list in order
the steps to be executed on whatever particular inputs are given
in the function call (they need not be called x,y, ...) and the
outputs can be stored under any variable names whatsoever.
Unlike a script le, all the variables used in a function are local to
that function. This means that the values of these variables are
only used within the function and do not over-write variables in the
workspace. For example if you assign the variable pi a value of 3
in the algorithm for some function (the sequence of steps executed
when the function is called) then you need not be concerned that
it might over-write the standard value of pi in the workspace. The
variables used to identify the inputs and outputs of a function are
also local to the function.
If a function is called without assigning its outputs to variables
then the rst of the outputs, only, is displayed on the screen.
Functions are the building blocks of larger programs. They feed
their results back to other functions and ultimately to the program
B.8 Function les 261
that interfaces with the user, that is, to a script le. The inter-
face tools (or functions) used by the script le may be more or
less sophisticated, but the hard computational work is done in the
component functions.
The fact that variables dened within a function are local to that
function, means that functions can be used in any program without
fear that the variables dened within the function will clash with
variables dened in the main part of the program. This also means
the programmer need not know the contents of a function, only
the information it needs and the information it will return. This is
exactly the case with built-in (primitive) functionsthe algorithm
used is not open to the user and in fact may be proprietory infor-
mation (information that might be thought to give this software
a commercial edge over competitors.) Many of the functions in a
sophisticated package like Mathematica fall into this category.
Some important points
The rst executable line in a function le must be preceeded
by a syntax line, that lists all the input variables and all the
output variables. This line distinguishes a function Sci-le
from a script Sci-le. The form of the syntax line is:
function [output_vars] = function_name(input_vars);
The output variables are enclosed in square brackets, as shown.
The input variables are enclosed with parenthesis, as shown.
A function does not have to have either input variables or
output variables, but most functions will both have inputs
and deliver outputs.
The function name should be the same as the Sci-le lename.
If the function name is Temp then the Sci-le name should be
Temp.sce.
Scilab is case sensitive by default, but your operating sys-
tem may not be. For example, while Scilab will recognize
that Temp and temp are two dierent variables, your operat-
ing system might not recognize that Temp.sce and temp.sce
are two dierent les.
Functions are executed by calling the function with the cor-
rect syntax, in exactly the same way as built-in functions are
used (that is functions such as sin, ceil).
values needed by the function should be passed as input vari-
ables to the function. The use of the input command in func-
tions should be avoided unless it is a user interface function.
the last statement of the function is the last statement in the
Sci-le. When the last statement is executed the function
262 Appendix B Programming with Scilab
returns and execution precedes from where the function was
called.
the return statement can be used to force an early return
from a function.
It is a good practice to place an endfunction on the last
line of a function. This makes it clear to other users exactly
where the function ends.
Example B.21: The following function returns the distance trav-
eled and the velocity of an object that is dropped. The input
variable is the elapsed time of falling.
// Function: fall
// Syntax: [dist, vel] = fall(t,v0)
// Input: t = list of elapsed times in seconds since
// body began a fall under gravity from
// rest with no resistance
// v0 = initial speed at the start of the fall
// Outputs: dist = list of distances fallen in metres
// from beginning of fall to times t
// vel = speed in metres/sec at time t
// Algorithm: Assumes vertical fall under constant gravity
// with no air or other resistance forces
// Source: Leigh Brookshaw 22/3/2000
// Last Modified: Tony Roberts, 2007
function [dist, vel] = fall(t,v0)
// The gravitational acceleration is assumed to be
g = 9.8; // metres/second/second
// Under constant acceleration (g) speed t is given by
vel = g*t + v0;
// and distances travelled by
dist = 0.5*g*t.^2 + v0*t;
endfunction
Put this text in a text le, say fall.sce, and load into
Scilab with the command exec(fall.sce) after every
time you edit the text le.
The following gives examples of using this function:
> [drop, velocity] = fall(5,0)
drop =
122.5000
velocity =
49
The output variables drop and velocity are scalars that
have been assigned the return values from the function.
B.8 Function les 263
> sec = 5;
> [drop, velocity] = fall(sec,0)
drop =
122.5000
velocity =
49
The input can be variables or explicit constants.
> secs=[1:5];
> [drop, velocity] = fall(secs,0)
drop =
4.9000 19.6000 44.1000 78.4000 122.5000
velocity =
9.8000 19.6000 29.4000 39.2000 49.0000
Input variable t can be a list. The output variables are then
vectors of corresponding values for distance and speed (and
consequently of the same length.
> fall(5,0)
ans =
122.5000
Here the result is not assigned to a variable. Note that in
this case the only answer returned is the value of the rst
variable in the function denition, namely dist. This means
to get all output from a function, you must assign all output
variables.
Exercise B.22: Use the above function to plot (on the one graph)
the distances travelled over a given number of seconds for
bodies starting their falls with dierent speeds by applying
the command plot(drop,secs) after each execution of the
function.
Example B.23: The following code rewrites the script of Exam-
ple B.8 so that the roots of a quadratic are calculated within
a function call
// Function : quadroot
// Syntax : [x] = quadroot(A,B,C)
// Input : A = coefficient of x^2
// B = coefficient of x
// C = constant coefficient
// in a quadratic polynomial
// Outputs : x = a list of the solutions
// of the equation Ax^2 + Bx + C = 0
// Algorithm: Uses the quadratic formula
// Source: Leigh Brookshaw 15/3/2000
// Last Modified: Tony Roberts, 2007
264 Appendix B Programming with Scilab
function [x] = quadroot(A,B,C)
// Calculate the square root of the discriminant
disc = sqrt(B^2- 4*A*C);
// Calculate and display the two roots
x = (-B + disc*[1,-1])/(2*A);
endfunction
Put this text in a text le, say quadroot.sce, and load into
Scilab with the command exec(quadroot.sce) after ev-
ery time you edit the text le. The result of running the
function might be stored in a variable name and passed to
other functions for further use.
Exercise B.24: Use the function of Example B.23 to assist you in
deciding on the plotting window for various quadratic poly-
nomials.
Since functions represent often repeated tasks that may be useful
in maintaining an application they are chosen and written with
some care and are well documented. In Scilab the rst block of
comments in a function can be accessed via the help command
command once the help les are built (see help help from sci).
For more sophisticated documentation, we would add keywords or
phrases that might be used by a person searching for a function to
do a particular task. Once (s)he has found the appropriate function
name, (s)he can then use help to get more detail on its use.
1. The rst comment line should contain the functions name
and other keyword descriptors that might help someone lo-
cate this function when they have a particular task to do but
dont know the name of the function that does it;
2. the next line should be the syntax line showing how this
function is to be called;
3. then the input variables should be listed, with units if appli-
cable;
4. followed by the output variables, with units if applicable;
5. input and output listings should be followed (or preceded)
by a description of what the function does if this is not
made clear by the description to the input and output vari-
ables; this statement should also include a description of the
algorithm that is used, if this has any special or unusual
featuresfor example, iterative solution by Jacobis method
or iterative solution by GuasssSeidel method;
6. divide the function code into recognisable blocks such as
Data Checking, Special Cases etc by the use of comments
if appropriate and also add comments to highlight where any
special features are implemented. Do not add inane com-
ments like
B.9 Control structures 265
v= v+2 % adds 2 to the value of v
but do not assume that even you will be able to follow your
own brilliant logic when you have long forgotten about how
you wrote the function, let alone someone else trying to read
the code for the rst time.
B.8.1 Local variables
The name of the input variables given in the function denition
line are local to that function. This means that when the func-
tion is called the input variables used in the call statement can
have dierent names. All variables used in the function are cleared
from memory after the function nishes executing. The function
in Example B.21, can be called using the statement
[drop, velocity] = fall(sec);
The variable sec is the elapsed time in seconds, but inside the
function this is called t. If, inside the function the variable t
was changed, it would not aect the variable sec in the calling
program. This is what is meant by the functions variables being
local to the function. This feature means that functions can be
written without concern that the calling program uses the same
variable names and therefore function les are portable, and need
not be rewritten every time they are used in a dierent program.
B.9 Control structures
In the execution of the function control passes from one line to
the next. However there are a number of situations in which it
is natural to want control to pass to dierent lines depending on
the value of computed variables. For example, input data may
maybe be treated dierently depending on when it is received (late
payment, assignments, etc).
Decisions to execute dierent lines of code in dierent circum-
stances are called branching decisions and most computer lan-
guages will provide a branching control structure for implementing
such decisions. Scilab provides the if ... then and the select
branching control structures. The tests that are made to determine
the blocks of code that should be executed often involve more than
one consideration and Scilab provides both relational and logical
operators to simplify the expression of these conditions.
Statements that alter the linear ow of the script are called control
structures
A control structure is also required when blocks of code are to be
repeated until a certain condion is met, for example, the computa-
tion of interest on a loan balance until such time as the loan balance
is paid o or repeated approximation to the solution of a problem
266 Appendix B Programming with Scilab
Table B.15: Scilabs relational operators
Relational operator Interpretation
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
~= not equal
until sucient accuracy is achieved. The repeated execution of a
block of code may be achieved by an iterative control structure or
loop. Scilab provides a while... loop which continues repeating
the block until a certain condition is met, and a for... loop which
repeats the block a given number of times.
The ow of control may also be disrupted by a recursive function
denitionthat is, a function denition which includes a call to the
function itself (with derent inputs of course). In this case, the
current function execution is suspended until a result is returned
from the within-function function call. Suspension will stack upon
suspension until a within-function function call produces a result.
Every recursively dened function must ensure that after some
nite number of recursions there will be a branch to an executable
line rather than to a further recursion. Such functions will be
very slow in executing and while they are very useful for solving
problems theoretically they are never as ecient as an equivalent
iterative solution and we will not use them much in this course.
B.9.1 Relational operations
To be able to create branching code we need to be able to ask
questions. For example, typical sorts of questions a code may ask
are:
Is the temperature greater than 100
C?
Is the height of the building less then 700 m?
Is that a car and is its speed equal to 60 km/h?
Questions that can be asked in a program only allow for two possi-
ble answers True or False. Scilab represents True with the value
%T and False with the value %F.
Relational operators are operators that compare two matrices of
equal size. The operator does an element by element comparison
between the two matrices and returns a matrix of the same size with
the elements set to %T if the comparison is true, and to %F otherwise.
An expression that contains a relational operator is a logical ex-
pression because the result is a matrix containing ones and zeros
B.9 Control structures 267
Table B.16: Scilabs logical operators.
Logical operator Symbol
and &
or |
not ~
that can be interpreted as true or false values, respectively.
Table B.15 contains a list of Scilabs relational operators.
Example B.25: Consider the following Scilab code:
a = [3 4 6];
b = [3 5 1];
c = a < b;
d = a ~= b;
e = a > b;
The result of this code is that the variables c, d, and e have
the values:
c = [F T F]
d = [F T T]
e = [F F T]
B.9.2 Logical operations
The logical expressions can be combined using the logical opera-
tors. The logical operators dened in Scilab are and, or and not,
and are represented by the symbols in Table B.16
Logical operators are used to combine logical statements created
using the relational operators into more complex logical expres-
sions; for example,
a<b & b<c
This operation is only valid if the two resultant matrices (repre-
sented by a<b and b<c) are the same size. The entry in the matrix
represented by this logical expression is %T (true) if the values in
the corresponding entries in a, b, and c, are such that a<b<c; oth-
erwise the entry is %F (false).
When two logical expressions are joined by or, entries in the re-
sulting matrix are %F (false) if both expressions are false, otherwise
it is %T (true). If two expressions are joined by and, entries in the
resulting matrix are %T (true) if both expressions are true, other-
wise it is %F (false). Logical expression preceded by not reverses
the value of the relational operation. For example, if a>b is true,
then ~(a>b) is false. In this example, the relational operation is
268 Appendix B Programming with Scilab
Table B.17: Precedence of operators
Operator Precedence Order of evaluation
() 1 Left to Right, Innermost rst
~ 2 Right to Left
^ 3 Left to Right
* / 4 Left to Right
\ 5 Right to Left
+ - 6 Left to Right
< > <= >= == ~= 7 Left to Right
& | 8 Left to Right
surrounded by brackets to modify the default precedence. See Ta-
ble B.17 for a list of the order of logical operations.
As it does with mathematical expressions, Scilab evaluates logical
expressions are evaluated from left to write. Unlike mathematical
expressions, if at any point in the calculation the logical answer
is known then the rest of the logical expression is ignored. For
example, if x=4 then the statement,
(x>3) |(cos(z)<0)
must evaluated to true, as the rst conditional part is true. This
means that the value of cos(z) need not be evaluated, and it is
not. Once a logical statement evaluates to a known result, extra
conditionals are ignored. The statement,
(x<3) & (exp(z)<1.0e4)
is false, irrespective of the value of exp(z). Scilab will not bother
to check whether exp(z)<1.0e4 because it is not needed.
Scilabs logical operators can also be applied to variables, not just
used with relational operations exclusively. For example, if the two
matrices A and B are the same size, then the result of A & B will
be a matrix with elements set to one where both A and B have
nonzero elements and zeros otherwise. The logical operators or
and not behave similarly.
Example B.26: If A = [6 4 0 1] , B = [0 2 6 2] , then
A&B = [F T F T]
~A = [F F T F]
A|B = [T T T T]
A<B&A = [F F F T]
Due to operator precedence the last example is equivalent to
(A<B)&A
Exercise B.27: Let A = [3 2 7 0] , B = [4 0 3 1] , C = [8 1 0 5] .
Without using Scilab, solve the following using the prece-
dence table and the denitions for the operators
B.9 Control structures 269
Table B.18: Some of Scilabs logical functions
Function Description
find(x) Returns the indices of the nonzero elements of
the vector x. If x is a matrix it returns the row
and column indices of the nonzero elements
isnan(x) Returns a matrix with ones where the elements
of x are Nans, zeros otherwise.
isempty(x) Returns a one if x is an empty matrix, zero oth-
erwise
~A; A | C; A <= B; A+B > C;
~C+B; C-4 > B; A ~= 7;
Check your answers using Scilab.
Exercise B.28: Scilab also has many logical functions. That is,
functions that return logical matrices. Using Table B.18 and
the Scilab help command, work out the result of the fol-
lowing commands. Do not use Scilab to solve the problems,
only to check your answers.
Let A=[3 2 7 0], B=[4 0 3 1], C=[8 1 0 5], and D=[].
What is the result of:
find(B); isempty(D); ~isempty(A); find(A>B);
B.9.3 Branch controls (conditional statements)
The if statement
The if statement is the most widely used conditional statement.
The form of a simple if statement is
if logical expression
statement group
end
If the logical expression is true, the statements between the if
statement and the end statement are executed. If the logical ex-
pression is false, then Scilab immediately jumps to the statement
following the end statement.
It is important to indent the statements within an if structure in
order to see the control ow easily.
Example B.29: One important use of an if statement, is to en-
sure that only valid parameters are passed to functions:
if x > 0
y = log(x);
end
270 Appendix B Programming with Scilab
if (x >= -1) & (x <= 1)
y = acos(x)*180/pi;
end
If statements can be nested when required. For example
if logical expression 1
statement group A
if logical expression 2
statement group B
end
statement group C
end
statement group D
Example B.30: The following function extends the code of Ex-
ample B.23 to allow the coecients of a number of quadratics
with real coecients to be entered at once and to return not
only the zeros but also the vertices of the parabolas they rep-
resent. Checks are made for error conditions. For example,
The coecient of the x
2
term cannot be zero. All coecient
vectors must be the same length.
// Function : quadroots
// Syntax : [x, v, M] = quadroots(A,B,C)
// Input : A = coefficients of x^2
// B = coefficients of x
// C = constant coefficients
// in the quadratic polynomials
// Outputs : x = the solutions of Ax^2 + Bx + C = 0
// v = the vertex coordinates
// both returned as 2 column matrices
// with one row for the results
// for each quadratic
// M = the original coefficients returned
// in the form of a matrix with one row
// for each quadratic
// Source: Leigh Brookshaw 15/3/2000
// Last Modified: Tony Roberts, 2007
function [x, v] = quadroots(A,B,C)
// If function fails output is empty
x = []; v = [];
// Data checking
// Check that all the coefficients have the same length
if (length(A) ~= length(B)) | (length(B) ~= length(C))
error(Not all coefficient arrays are of equal length);
end
// Check that all the coefficients are real. Tests such as
// these are madein case the coefficients have been passed
// to this function from some other computation.
if ~isreal(A)
B.9 Control structures 271
error(Not all elements of A are real!);
end
if ~isreal(B)
error(Not all elements of B are real!);
end
if ~isreal(C)
error(Not all elements of C are real!);
end
// Check that no value of A is zero
if find(A==0)
error(No elements of A are allowed to be zero);
end
// Computing the Output
M = [A;B;C]; // the coefficients in a matrix
xs = -B./(2*A); // vertex abscissae
ords = A.*xs.^2 + B.*xs + C; // ordinates of vertices
v = [xs;ords]; // vertex coordinates
disc = B.*B - 4*A.*C; // the value of the discriminant
x = ([xs;xs]+([1,-1]*sqrt(disc))./[(2*A);(2*A)]) // zeros
endfunction
The if-else statement
The else clause added to an if statement means that two blocks
of code can be specied. One to be executed if the the logical
expression is true, the other if it is false. For example
if logical expression
statement group A
else
statement group B
end
If the logical expression is true, then statement group A is exe-
cuted. If the logical expression is false, then statement group B
is executed. The statement groups can also contain if and/or
if-else statements to provide a nested structure.
Example B.31: The velocity of a cable car between two towers.
Assume that the scalar r is the distance from the nearest
tower. If the cable car is within 30 metres of the tower, the
velocity is calculated using the equation velocity = 0.425 +
0.00175 r
2
. If the cable car is further away from the
tower, the velocity is calculated using the equation velocity =
0.625 + 0.12 r 0.00025 r
2
.
The correct velocity is calculated with the statements
if r <= 30
velocity = 0.425 + 0.00175*r^2;
else
272 Appendix B Programming with Scilab
velocity = 0.625 + 0.12*r - 0.00025*r^2;
end
Notice that control structures can be executed in the inter-
active environment, besides being used within functions.
The if-elseif-else statement
When several levels of if-else statements are nested, it may be
dicult to determine which logical expressions must be true (or
false) to execute each set of statements. In this case, the elseif
clause is often used to clarify the program logic.
The else and elseif clauses are optional in an if statement. The
general form of the if statement is:
if logical expression 1
statement group A
elseif logical expression 2
statement group B
elseif logical expression 3
statement group C
.
.
.
else
statement group D
end
If logical expression 1 is true, then only statement group A is ex-
ecuted. If logical expression 1 is false and logical expression 2
is true, then only statement group B is executed. If logical ex-
pressions 1 and 2 are false and logical expression 3 is true, then
statement group C is executed. If none of the logical expressions
are true then statement group D is executed. If more than one
logical expression is true, the rst logical expression that is true
determines which statement group is executed.
The select statement
The select statement provides an alternative to a if-elseif-else
construct. Though anything programmed using a select state-
ment can be programmed using an if structure, often the code is
more readable using the former.
The structure of the switch statement is:
switch input expression
case value 1 then
statement group A
case value 2 then
statement group B
B.9 Control structures 273
.
.
.
else
statement group D
end
The input expression of the select statement must evaluate to a
scalar or a string. The value of the input expression is compared to
each case value. If a match is found then the statements following
the case statement are executed.
At most only one case statement group is executed, then execution
resumes with the statement after the end statement.
If no case statement matches the input expression then the state-
ments following the else statement are executed. The else state-
ment is optional.
Below is an example of a case statement, where the select variable
direction contains a character string (remember that convstr(a,l)
is a Scilab primitive function that takes a text as input and re-
turns it all in lower case.)
select constr(direction,l)
case north then
angle = 0;
disp(Direction: North);
case south then
angle = pi;
disp(Direction: South);
case east then
angle = 0.5*pi;
disp(Direction: East);
case west then
angle = 1.5*pi;
disp(Direction: West);
else
angle = %nan;
disp(Direction: Unknown);
end
B.9.4 Iteration controls (explicit loops)
Scilab contains two constructs for explicitly looping, the for state-
ment and the while statement. The for statement is used when
the number of times the block of code must be looped over is known.
The while statement is used when the number of times the block
of code must be looped over is unknown. The looping is terminated
when a specied condition is satised.
274 Appendix B Programming with Scilab
The for statement
The general form of the for statement in Scilab is as follows:
for index = expression matrix
statement group
end
The statements in the statement group are repeated as many times
as there are columns in the expression matrix (which could also be
a scalar or a vector). Each time through the loop, the index has
the value of one of the columns in the expression matrix.
Some examples of the for statement:
calculating the factorial of 20
factorial = 1;
for i=2:20
factorial = factorial*i;
end
Although this computation is far better done by simply prod(1:20).
Multiply the elements of an array
product = 1;
A = [6 8 9 10 2 -5 1 7];
for i=A
product = product*i;
end
This is also much better done by prod(A).
The rules for a for loop are the following:
The index of the for loop must be a variable.
If the expression matrix is the empty matrix, the loop will
not be executed. Control will pass to the rst statement
following the end statement.
If the expression matrix is a scalar, then the for loop will
be executed once only. The index variable will contain the
value of the scalar.
If the expression matrix is a row vector, then each time
through the loop, the index will contain the next value in
the the vector.
If the expression matrix is a matrix, then each time through
the loop, the index will contain the next column in the the
matrix.
B.9 Control structures 275
On exiting the for loop, the index contains the last value
used.
The colon operator can be used to dene the expression ma-
trix. The syntax is:
for index=initial:increment:limit
The number of times the loop will be executed can be calcu-
lated from the equation:
oor
limit initial
increment
+ 1
If this value is negative, the loop is not executed. If increment
is omitted, it is assumed to be one.
Lastly, and the most important rule of all, a for loop must
never, never, ever be the innermost loop in a computation.
The innermost loop must always, always, always be a natural
vector/matrix command. Two examples, are the two exam-
ples given above: the for loop to compute a product must
be replaced by the prod function. See further discussion in
Section B.9.5.
Example B.32: Suppose the cable car distance from the pylon r,
of Example B.31, is a vector. Then Example B.31 will have
to modied to calculate a vector of velocities.
// Initialize the velocity array to same size as r .
velocity = zeros(r);
// Loop over the distance array and calculate velocities
for k = 1:length(r)
if r(k) <= 30
velocity(k) = 0.425 + 0.00175*r(k)^2;
else
velocity(k) = 0.625 + 0.12*r(k) - 0.00025*r(k)^2;
end
end
However, the above code has a for loop as the innermost loop
and so violates the last criterion above. Rewrite it using nat-
ural matrix/vector modes of computation. After initialising
the velocity to a correct size matrix, simply
k=find(r<=30);
velocity(k) = 0.425+0.00175*r(k).^2;
k=find(r>30);
velocity(k) = 0.625+0.12*r(k)-0.00025*r(k).^2;
Use the for loop only when the inside of the loop is less
trivial.
276 Appendix B Programming with Scilab
The while statement
The while loop is a structure for repeating a set of statements as
long as a specied condition is true. The general form of the while
loop is:
while expression
statement group
end
If the expression is true or all elements nonzero, then the statement
group is executed. The expression is normally a logical expression.
After the statements are executed, the condition is re-tested. If the
condition is still true, the group of statements are executed again.
When the condition is false, control jumps to the rst statement
following the end statement. If the expression is always true (or is
a value that is nonzero), the loop becomes an innite loop!
Example B.33:
// To sum the positive elements of the vector x
// use the length command to find the
// number of elements in x
sum = 0; k = 1;
while (k <= length(x)) & (x(k) >= 0)
sum = sum + x(k);
k = k + 1;
end
Of course, again this violates our last criteria. Instead, in
practise code simply
sumx=sum(x(find(x>=0)));
Use while loops when the computation inside the loop is not
so simple.
Exercise B.34: Write a function containing the code of Exam-
ple B.33. Test the function and also modify it so that the
condition statement of the while loop is reversed, that is
while (x(k) >= 0) & (k <= length(x))
Now test the function again. Explain why is there now an
error in the script.
A danger of while loops is that they may never terminate. This
obviously occurs if the condition is always true. A loop counter
can be added to the condition to ensure that the loop terminates.
For example, in the code below, the termination condition we are
interested in is (a>=0), this is assumed to occur within 100 loops, if
B.9 Control structures 277
it does not then an error has occurred. The variable count ensures
the loop will not be innite.
count = 1;
while (a < 0)
...
count = count + 1;
if count > 100
error(Loop failed to terminate!);
end
end
To break out of an innite loop, and terminate execution of a script
or function, you can press Control C on the keyboard. That is,
hold down the Ctrl key and press C simultaneously.
Exercise B.35: Timber management needs to determine how
much of an area to leave uncut so that the harvested area
is re-forested in a certain period of time. Assume that the
reforestation takes place at a known rate per year depending
on climate and soil conditions. If the reforestation rate is ,
then the reforestation equation is (Forested area this year) =
(Forested area last year) (1 + ) . Assume that there are
11,000 hectares total, with 4,500 hectares uncut, and the re-
forestation rate is 0.03 hectares/year. Write a function that
returns a reforestation vector with the followinghelp lines in
its denition.
// Function: reforest
// Syntax : hectares = reforest(years, rfrate, inhec)
// Input:
// years - the number of years to calculate
// the reforestation
// rfrate - the reforestation rate in hectares/year
// inhec - the initial forest area in hectares.
// Output:
// hectares - a vector that lists the forest area
// in hectares for each year. The length
// of the vector is the same as the
// number of years input parameter.
//
function hectares = reforest(years, rfrate, inhec)
Exercise B.36: Write a script to print a table showing the num-
ber of hectares re-forested at the end of each year, after asking
the user to enter the number of years to be used in the table.
Exercise B.37: Modify the program of Exercise B.35 so that the
user can enter the number of hectares, and the program will
determine how many years are required for the number of
hectares to be re-forested.
278 Appendix B Programming with Scilab
The break statement
Use the break statement to break out of a for loop or a while
loop before it has completed. This statement is useful if an error
condition is detected within the loop. This statement is also use-
ful for terminating an iteration when the desired result has been
computed. The loop is terminated at the point where the break
command is executed.
B.9.5 Implicit loops
If you are familiar with more traditional programming languages
such as fortran, basic or C, the discussion on looping above will
be familiar. The for and while looping discussed has its coun-
terparts in many languages. However, since Scilab was designed
to make matrix manipulations easy one would not expect to have
to use loops to implement operations like matrix multiplication or
vector addition but to nd them encapsulated in primitive func-
tions. It turns out that these primitives nd surprising uses and
that in many situations where a classical scalar language needs
loops to complete a calculation, array processing primitives handle
the computation without any apparent looping.
See Examples B.32 and B.33.
These codes use the find function to create a vector k, that con-
tains the indices of all the elements in x that are greater than zero.
For example, consider a vector x that is dened as follows:
x = {7, 3, 2, 4, 5, 6}.
The command k=find(x>0) returns the following:
> k=find(x>0)
k =
1 3 4
This means that elements x
1
, x
3
and x
4
are the only positive values
in vector x.
In the second line, the statement xp=x(k), is a vector that only
contains the positive elements of x. For our example we should get
a vector contain the elements x
1
, x
3
and x
4
of x. Thus xp should
contain the values 1,3 and 4 (see output below to verify this).
> xp=x(k)
xp =
7 2 4
The Scilab function sum, simple sums all of the elements of this
vector (see output below).
> sumx=sum(xp)
B.9 Control structures 279
sumx =
13
Scilab was designed to process matrix operations rapidly. The
more traditional for and while loops have to be interpreted which
takes an enormous amount of time. Implied loops utilize specially
designed operators within Scilab. This means the processing is
extremely rapid. An implied loop in Scilab executes up to a
hundred times faster than the equivalent explicit for or while
loop.
A disadvantage of the implied loop is that Scilab code can become
terse and hard to understand. If you develop your skill in thinking
in vector, matrix and array terms then this brevity will soon appear
as elegance of expression and the scalar version will seem clumsy
and pedestrian. You should make every eort to think in these
terms as it constitutes parallel processing at the software level.
B.9.6 Using functions and scripts together
As a mini-application a script can be used as a driver for a par-
ticular function. As such it can interrogate a user for the required
inputs and make the function call with the correct syntax. This use
is particularly attractive when the syntax for a function is rather
tedious to nd or remember. Because of the danger of over-writing
workspace variables when one uses a script, if scripts are going to
be used in this way to drive functions then it is a wise practice to
either give the variables long and unlikely names or as the rst in-
teraction with the user to check that the names used can be safely
over-written. For example, in a workspace for calculus computa-
tions the names d and S might very well be used for functions that
compute dierences between list elements and sequences of partial
sums of series. Such names will be very convenient in that setting
so that one could write, for example, d(y)./d(x) for derivative
approximations, and S(y.*d(x)) for approximations to the inte-
gral (as we shall do in other modules of this course). Of course
these simple single character names are in grave danger of being
over-written by careless assignments in the interactive session or a
script.
Exercise B.38: A small rocket is being designed to make wind
shear measurements in the atmosphere. Before testing be-
gins, the designers have developed a model of the rockets
trajectory. The height in metres above the ground at time t
in seconds is
height (metres) = 20 + 2.13 t
2
0.0013 t
4
+ 0.000034 t
4.751
Write a function that takes the time in seconds and returns
the height. It should return a vector of heights when the time
is given as a vector.
280 Appendix B Programming with Scilab
Write a driver script to run your function.
Exercise B.39: Using the function from Exercise B.38, write a
script to compute the height of the rocket from t = 0 to the
time it hits the ground. Use increments of one second. If
the rocket has not hit the ground after 80 seconds, stop the
program and print out an error message. Have the script
print out a table of times and heights of a size determine by
the user and on request plot the results.
Exercise B.40: Using the function from Exercise B.38, write a
program to compute the time at which the rocket reaches the
highest part of its trajectory and the time at which it impacts
the earth. Both should be accurate to one second.
B.10 Numerical programming
B.10.1 Modular Programs
Any problem, that can be solved by a computational program, can
be solved in one monolithic program contained within one le. In
fact, since a program is just a string of bits, we could convert this
bit string into a number to base 10 and present this single number
as an solution to the problem. This is not particularly helpful if
you have the job of maintaining the program (that is, modifying it
to meet current needs).
There are a number of reasons for avoiding a monolithic program:
the project as a whole, and it could be a large one, has to be
understood in its entirety to write a monolithic program. If
it is not understood in its entirety then many rewrites will
be necessary to incorporate all aspects of the project.
large cumbersome les are dicult to work with.
large monolithic programs are dicult to understand, for the
author and anyone else.
Sensible programming attempts to identify the key operations re-
quired to solve the problem and the tools that will help in putting
the solution together. These tasks are of course solved by running
functions. The basic rule about functions is that each function
should perform one task and one task only. The project analy-
sis should be task oriented, each task coded and tested separately.
The main program pulls together these disparate pieces with a
script that mainly contains calls to functions. The advantage of
this approach is:
many programmers can work on the problem simultaneously.
B.10 Numerical programming 281
a monolithic project is broken down into smaller manageable
chunks.
if each function performs one task, then the nal code is easier
to read and understand.
it is easier to work with smaller les.
Functions themselves should also be written in a block like man-
ner. That is similar tasks should appear together in the function.
Initialization of all variables should appear together at the start of
the function, all checks on input variables should appear together.
For example:
1. Help comments: name and keywords; syntax, inputs and out-
puts
2. function [output variables] = fname(input variables)
3. Test that the input variables are valid.
4. Initialize all variables that need it.
5. Load any data that might be needed.
6. Computational algorithm for function.
The above is an outline for the design of a function. Particular
circumstances will dictate the design of any individual function,
but the steps above should be borne in mind whenever a function
is written.
B.10.2 Debugging
Debugging a program is the process of nding and removing the
bugs or errors. Such errors usually fall into one of the following
categories:
Syntax errors such as omitting a parenthesis or comma or
spelling a command name incorrectly. Scilab usually detects
the more obvious errors and displays a message describing the
error and its location.
Runtime errors occur while the program is running and fall
into a number of categories:
Errors due to incorrect logic. They do not necessarily
occur every time the program is executed; the occur-
rence may depend on the type of input data. A common
example is division by zero. A logic error is caused by
the author not anticipating all possible eventualities.
Errors due to incorrect method. This can be a very sub-
tle error, recognising that the numerical method being
used is incorrect for the problem being solved. Normally
this can only be xed by rewriting the program using a
282 Appendix B Programming with Scilab
better method for the problem. Unfortunately, this er-
ror might only be recognised after an immense amount
of eort has been expended writing the program. It is
important when deciding on which numerical method
to use to solve a problem that the limitations of the
method are well understood.
The Scilab error messages usually allow you to nd syntax errors.
However, runtime errors are more dicult to locate and are more
dicult to spot. It is important to check all answers produced by
programs. Never trust the answer from a program. Some tests
that should always be employed with computer solutions are:
always check the order of magnitude of the solution. Is it
reasonable?
if the solution has units, check that the order of magnitude
of the solution is reasonable for those units.
plot the answers, and see if the plot looks reasonable.
If you have tested the solution and think there is an error, then to
locate the error, try the following:
Always test your program with a simple version of the prob-
lem, whose answer can be checked by hand calculations. If
your program uses functions, test the functions individually,
by writing test scripts for each function.
Display any intermediate calculations by removing semicolons
at the end of statements.
Use the Sci-le Debugger. The Scilab Debugger is a set of
commands that allow you to stop a script during execution
and examine or modify variables.