Scilab Primer
Scilab Primer
Graeme Chandler
Mathematics Department
The University of Queensland
Stephen Roberts
Department of Mathematics
Australian National University
August 7, 2002
Contents
1 Introduction. 3
1.1 Learning Scilab . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Further References . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Starting Scilab . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Typing Commands . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Simple Calculations 6
2.1 Basic Arithmetic. . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Complex Numbers. . . . . . . . . . . . . . . . . . . . . . . . . 7
3 Help in Scilab 8
3.1 The Help Command . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 The Help Window . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 Help on the Web . . . . . . . . . . . . . . . . . . . . . . . . . 9
1
6 Polynomials 20
7 Graphs 21
7.1 Function Plotting . . . . . . . . . . . . . . . . . . . . . . . . . 21
7.2 Component Arithmetic . . . . . . . . . . . . . . . . . . . . . . 22
7.3 Printing Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7.4 Graphs in Reports . . . . . . . . . . . . . . . . . . . . . . . . 24
7.5 Saving Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.6 Advanced Graphics . . . . . . . . . . . . . . . . . . . . . . . . 25
2
1 Introduction.
High level scientific computing environments such as Matlab, Rlab, Octave
and Scilab are an enjoyable way to solve problems numerically. The compu-
tational problems arising in most undergraduate courses can be solved much
more quickly using these environments, than with the standard program-
ming languages (Fortran, indexFortran C, Java, etc.). It is particularly easy
to generate some results, draw graphs to look at the interesting features, and
then explore the problem further. By minimizing human time, it is partic-
ularly useful in the initial investigation of real problems; even though they
may eventually have to be solved using more computationally efficient ways
on super computers.
Matlab is by far the most popular of these environments, it has a large
user base and many resources are available on the Web. Indeed a version
of this document “An Introduction to Matlab” is available on the web at
http://www.maths.uq.edu.au/~gac/mlb/mlb.html.
The other three packages are public domain or open source packages. In
this document we concentrate on Scilab. Scilab provides an environment
which uses matrices (both full and sparse) as it basic data type. Algorithms
are available for the numerical solution of differential equations, optimisation
problems, interpolation and quadrature. High quality fortran and C codes
can be easily linked into Scilab. The package provides excellent 2 and 3
dimensional graphics which can be readily incorporated into reports and
publications. Simple user interfaces can be built using Scilab. The package
is also available for all standard machines, PC’s, Macs, LINUX and Unix.
All these attributes (and more) lead us to use Scilab as the basic package
for our computational science courses at the Australian National University.
Indeed the ability for students to have access to the software on their home
machines is the main reason for a choice of open software. We feel that Scilab
provides the best compromise of free software and a sophisticated range of
builtin facilities.
3
The best way to used this introduction is to sit down at a computer and
type in the commands as they are described. Look at Scilab’s response, and
check that the answers are what you expect. It is also a good idea to do
the small exercises. It makes sure that the commands become part of an
active Scilab vocabulary. Each lesson should take less than one hour. More
information about any Scilab command can be found by using the on line
help features described in lesson 3.
These notes assume basic familiarity with the Windows interface. For
instance, you need to know about
If you are unsure about this, seek help from another student or tutor.
1. First sit down at a PC. If necessary, close any programs left running
by a previous user. The simplest way is to use the Windows ‘Start’
button then the ‘Shut Down’ option.
3. You should now see the standard Windows desktop with a screen of
icons.
4. Find the icon labelled ‘Scilab’ and double click on it. After another
pause, the Scilab logo appears briefly, then the ‘Scilab Command Win-
dow’ remains on the screen. It ends with the words:-
4
===========
S c i l a b
===========
scilab-2.6
Copyright (C) 1989-2001 INRIA
Startup execution:
loading initial environment
-->
• Any typing error can be corrected before the [enter] key is pressed.
– Use the keypad left and right arrows or the mouse to move to the
error.
– Use the [del] key to delete the mistakes, and then type in the
correction.
– When the line is correct, just press [enter] to send the command
to Scilab. (It is not necessary to go to the end of the line.)
Usually errors are not noticed until Scilab displays an error message.
However it is not necessary to retype the whole command.
– Just press the keypad up arrow and the previous command ap-
pears.
– Make the necessary corrections and press [enter] to run the cor-
rected command.
5
Now go on to the first lesson. Type in all the commands as they are
shown, and make sure the Scilab response is what you expect.
2 Simple Calculations
2.1 Basic Arithmetic.
The simplest way to start with Scilab is to use it for simple calculations.
Scilab has a wide range of functions and is able to use complex numbers as
well as reals. The following simple commands have obvious meanings. Type
them in and see what happens.
In the examples below, all the text after the // is just a comment or an
explanation. You do not have to type it in. It would just be ignored by
Scilab.
// The words after ‘//’ are comments
// and explanations. Do not type them in.
(-1+2+3)*5 - 2/3 // The four arithmetic operations
2^3 // Means 2 to the power 3
%pi // The mathematical constant pi
exp( sin( %pi/2 ) ) // The usual functions are provided
// log, log10, cos, tan, asin, ...
%e // The mathematical constant e
Like a calculator, Scilab does all calculations correct only to about 16
significant decimal digits. This is enough accuracy for most purposes. For
convenience, usually only the first 5 significant digits are displayed on the
screen. Some more examples.
%pi
22/7 // pi is not the same as 22/7!
11*(15/11) - 15 // This shows there is roundoff error
// when Scilab uses fractions.
cos( %pi/3 ) // These are familiar trig functions.
sin( %pi/6 ) // Note Scilab always uses radians.
Scilab also uses variables to store intermediate answers. A variable can
have almost any name, but it must begin with a letter. Scilab distinguishes
between upper and lower case letters.
x = 2+3
y = 4+5
result1 = x/y
6
Sometimes the values of intermediate calculations are not needed and
we do not want them to be displayed. If a semicolon (;) is placed after a
command, the results are not displayed.
A number of commands can be placed on the one line, provided they are
separated by a comma (,) or a semicolon (;). (Use a semicolon, unless you
want the answer displayed.)
Parentheses can be used to make expressions clearer. Thus the last calcula-
tion could have been written as
ratio = (2+3)/(x+4)
Exercise 1 In this exercise, save retyping by using the up arrow to edit the
previous commands! Remember that multiplication is done with a ‘∗’, it is
not enough to put numbers next to each other.
x = 2 + 3*%i , y = 1 - 1*%i
z1 = x - y , z2 = x * y , z3 = x / y
abs( x )
real( x )
imag( x )
atan( imag(x) , real(x) ) // The argument of a complex number
7
Scilab’s facility with complex numbers is handy, as using complex num-
bers often involves complicated arithmetic. Indeed, as the previous example
shows, Scilab will effortlessly work out functions of complex numbers that
are √
difficult to do from first principles. But be careful about
√ the name used
for −1. When Scilab starts, the variable %i contains −1. It is sensible
to avoid using variables with names that start with %.
Here are two more complex calculations. Scilab can be used to demon-
strate one of the most important relations in Mathematics: that eπi = −1.
(At least to within round off error!).
exp( %pi*%i ) + 1
%i^%i
Exercise 2
2. If y = ii , what are iy and y i ? Can you work this out without Scilab?
3 Help in Scilab
3.1 The Help Command
The help command is the easiest way to find out more about specific Scilab
commands. If you have forgotten small details, for example. The command
help <name> gives information about the Scilab command <name>.
Note that often the help information provides an example of how the com-
mand is used. This can be particularly useful when experimenting with a new
command. You can use cutting and pasting to run the example commands.
In Scilab the apropos command can also be used to search for relevant
information.
8
3.2 The Help Window
It is also possible to get help by clicking on the help menu above the com-
mand window. From the help menu, select the help dialog item and the
list of help topics is displayed. The advantage of this method is that it is
possible to navigate around different topics and zero in on useful commands.
For example, in the help dialog window click on the chapter ’Linear Alge-
bra’. Then find the item ’linsolve’. Once found you click on ’show’ to see
the relevant help page. Note that double clicking doesn’t work in windows
Scilab version 2.6 and there is a slight bug when you change chapters and
scroll to new items. Choosing the item a second time seems to work.
Generally the help window is a good way to explore Scilab’s commands.
Exercise 3
(a) How do you find sin−1 (.5) in Scilab? Use help to find out.
(b) If x = .5, is sin(sin−1 (x)) − x exactly zero in Scilab?
(c) If θ = π/3, is sin−1 (sin(θ))−θ exactly zeros in Scilab? What about
θ = 5π/11?
3. Look for information about logarithms. Note that searching for loga-
rithms fails where as logarithm succeeds. There are 8 entries, including
the command, logm, for calculating the log of a matrix!
4. To wind down, use the Scilab menu command demos. This brings a
menu of demonstrations and examples to explore.
9
4 Plotting Lines and Data
This section shows how to produce simple plots of lines and data.
Suppose we wish to plot some points. For example we are given the
following table of experimental results.
To work with the data in Scilab set up two column vectors x and y.
(Vectors are discussed in detail in the next lesson; but we can use them to
draw graphs without knowing all the details.) To graph y against x use the
plot command.
plot2d(x,y, style=-1)
The graph should now appear. (If not, it may be hidden behind other win-
dows. Click on the icon ‘Figure No. 1’ on the Windows task bar to bring the
graph to the front.)
This graph marks the points with an ‘+’. Other types of points can be
used by changing the style=-1 in the plot2d command. (Use help plot2d
to find out the details.)
Exercise 4 Experiment with different values for the style. Negative values
give markers, positive values coloured lines. As you experiment you should
erase the previous plot. Use the command
xbasc()
From the graph it is clear that the data is approximately linear, whereas
this is not so obvious just from the numbers. Good graphs quickly show what
is going on!
When you have finished looking at the graph, just click on any visible
part of the command window, or on the Scilab icon on the task bar. More
commands can then be typed in.
10
Exercise 5
2. Plot the above data with the points joined by lines (use help plot).
4. Find out how to add a title to the plot. (Hint: Use the commandhelp plot.
At the end of the help output there is a list of related commands. Find
out about one of these with another use of the help command.)
Note that x_vals contains the x–coordinates, y_vals contains the y–coordinates,
and the two points are joined by a line because we don’t specify a style (de-
fault style is a line).
The line of best fit can be found using the datafit function.
11
The data is hard to find on this graph Marking individual points improves the graph
2.5 2.5
2 2
1.5 1.5
1 1
0.5 0.5
0 0
0.5 1 1.5 2 0.5 1 1.5 2
Uses the command plot(x,y). What was the command?
This simple command does not present the data here very well. It is hard
to see how many points were in the original data. It is really better to plot
just the points, as the lines between points have no significance; they just
help us follow the set of measurements if there are several data sets on the
one graph. If we insist on joining the points it is important to mark the
individual points as well
Exercise 6 Change the above plot command to show the data more clearly by
plotting the data points as small circles joined by dotted lines. (Hint: There
should be a third argument in the plot command containing the symbols for
a line of dots and the marker type circles; and perhaps a colour symbol as
well!). Use help plot2d to see the possible arguments.
12
4.2.2 Choose a good scale
In the example in this section, it was easy to see the relationship between x
and y from the simple plot of x against y. In more complicated situations,
it may be necessary to use different scales to show the data more clearly.
Consider the following model results
n 3 5 9 17 33 65
.
sn .257 .0646 .0151 3.96×10−3 9.78×10−4 2.45×10−4
0.3
−1
10
0.25
0.2
−2
10
0.15
0.1 −3
10
0.05
−4
0 10 0 1 2
0 20 40 60 80 10 10 10
A good plot reveals a relationship in the data.
n = [ 3 5 9 17 33 65 ]’;
s = [ 2.57e-1 6.46e-2 1.51e-2 ...
3.96e-3 9.78e-4 2.45e-4 ]’ ;
13
In fact it is hard to read the values of sn back from the graph. However a
plot of log(n) against log(sn ) is much clearer. To produce a plot on a log
scale we can use either of the commands
It reveals there is almost a linear relationship between the logs of these two
quantities.
Exercise 7 1. Using help plot2d find a command which will use a log
scale only for the sn data. Is this better or worse than the log-log plot?
2. Add a title to the last plot above and label the X and Y axes.
x1 + 2x2 − x3 = 1
−2x1 − 6x2 + 4x3 = −2
−x1 − 3x2 + 3x3 = 1
14
In first year Mathematics the problem is rewritten in matrix-vector no-
tation. We introduce a matrix A and a vector b by
1 2 −1 1
A = −2 −6 4 , b = −2 .
−1 −3 3 1
Now we want to find the solution vector x = [x1 , x2 , x3 ] so that
Ax = b.
In spite of the new notation, it is still just as unpleasant to find the solution.
In Scilab, we can set up the equations and find the solution x using simple
commands.
// Set up a system
A = [ 1 2 -1; -2 -6 4 ; -1 -3 3 ] // of equations.
b = [ 1; -2; 1 ]
x = A\b // Find x with A x = b.
15
1.0e-004 *
1.2300e-05
0.1234 or 4.4400e-06
0.0444
The user can control which form is used by using the command format.
Essentially the full accuracy can be seen using format(’e’,20).
2. Suppose the middle element is changed from -6 to -5. Can Scilab solve
this third system? Explain what has happened.
16
5.3 Creating Matrices
Scilab also provides quick ways to create special matrices and vectors.
c = ones(4,3)
d = zeros(20,1)
I = eye(5,5)
D = diag( [2 1 0 -1 -2] )
L = diag( [1 2 3 4], -1 )
U = rand(5,5) // U is a 5 x 5 matrix
// of uniformly distributed random numbers.
R = rand(5,5,’normal’); // R is a 5 x 5 matrix
// of normally distributed random numbers.
B = [1 1 0 0
0 2 1 0
0 0 3 1
0 0 0 4 ] // Rows can be separated by
// making a new line as well as using ‘;‘.
c = [1; 0; 0; -1]
5*B // Multiply scalars and matrices.
B*c // Multiply matrices and vectors.
A*B // Matrix by matrix multiplication.
B*A // Note: AB is not the same as BA !
Exercise 10
17
1. Calculate inv(A)*A and A*inv(A). Do they give the expected result?
(Use the help command if you can’t guess what the inv command does.)
3. Verify that the Scilab command A^(-1) can also be used to form the
inverse of A.
Exercise 11
using \. Check that the computed solution does actually satisfy the
equations (i.e. check that b − Ax = 0, apart from rounding errors).
18
2. Use rand(n,m,’normal’) to generate a 700 x 700 matrix, A, and a
column vector b of length 700. Solve the system of equations Ax =
b using the commandsx = A\b and x = inv( A ) * b, timing each
command with the timer() command. Which command is the faster
and why? (Hint: before working with these large matrices use the clear
command to remove all variables from Scilab’s memory. This frees
up enough memory to squeeze in this largish problem. If you have
problems, try a smaller system of equations that fits onto the computer
you are using.)
3. Set up the 10 × 10 Hilbert matrix. The ij component is given by 1/(i +
j − 1). You can use feval to produce the matrix given the function
deff(’z=f(x,y)’,’z=1.0/(x+y-1)’)
Create a right hand side vector b by b = A(:,1). We are now going to
solve the equations Ax = b. This is a common test problem in linear
algebra. (What is the true solution x to the equations Ax = b?)
4. Extend part (3) by solving a slightly different problem. Let the right
hand side vector b be the first column of A, divided by 3; i.e. b = A(:,1)/3.
(What is the solution to the equation Ax = b with this new right hand
side?)
(a) What is the size of the error and the size of the residual when the
\ is used to solve the system with the new right hand side?
(b) Extend the computation further by letting the right hand side be the
j th column of A divided by 3; i.e. b=A(:,j)/3for j = 1, 2, 3, . . . , 10.
Complete the following table.
19
Column j Size of the Residual Size of the Error
1 . .
2 . .
.. .. ..
. . .
10 . .
6 Polynomials
We can use Scilab procedures to deal with polynomials. The polynomial
a0 + a1 x + . . . + am−1 xm−1 + am X m can be represented in Scilab symbolically.
In the following example, −4 − 3x + x2 is represented by the vector of
coefficients [−4 − 3 1] and by a polynomial p We setup the polynomial with
the command
v = [-4,-3,1]
p = poly(v,’X’,’coeff’)
z = roots( p )
z(1)^ 2 -3*z(1) -4 // Two ways to evaluate the poly.
horner(p,z(1)) // at the first root.
derivat(p,’x’) // Calculate the derivative of the polynomial
20
The Scilab polynomial methods generalise to rational functions. For in-
stance
x = poly(0,’x’) // Seed a Polynomial using variable ’x’
p = x^2 - 3*x - 4 // Represents x^2 - 3 x -4
r = x/p // Represents the rational
// function x/(x^2 - 3 x -4)
Exercise 12
1. The polynomial x2 − 3x − 4 has real roots, but x2 − 3x + 4 has complex
roots. Find these complex roots with roots.
2. Experiment with rational functions, i.e. create, evaluate and differen-
tiate the rational function x/(x2 − 3x − 4).
7 Graphs
Consider the problem of graphing functions, for example the function
f (x) = x|x|/(1 + x2 )
over the interval [−5, 5].
21
7.2 Component Arithmetic
The new method is illustrated in the following lines.
x = (-5:.1:5)’ ;
y = x .* abs(x) ./ ( 1 + x.^2) ;
plot2d( x , y )
The first command produces a vector of x values from -5 to 5 in steps of
.1. That is the column vector x = [−5, −4.9, · · · , 0, · · · 4.9, 5]0 . The vector y
contains the values of f at these x values. As there are so many points the
graph of x against y looks like a smooth curve.
The novelties here are the operators .* , ./ and .^ in the second com-
mand. These are the so called component–wise operators. In the above
example x is a column vector of length 101 and abs(x) is the column
vector whose ith entry is |xi |. The formula x*abs(x) would be wrong, as
this tries to multiply the 1 × 101 matrix x by the 1 × 101 matrix abs(x).
However the component-wise operation x.*abs(x) forms another vector of
length 101 with entries xi |xi |. Continuing to evaluate the expression using
component-wise arithmetic, we get the vector y of length 101 whose entries
are xi |xi |/(1 + x2i ). More explicitly
−5 | − 5| −5 × | − 5|
−4.9 | − 4.9| −4.9 × | − 4.9|
x = −4.8 , abs(x) = | − 4.8| , x.*abs(x) = −4.8 × | − 4.8|
.. .. ..
. . .
−5 × | − 5|/(1 + (−5)2 )
−4.9 × | − 4.9|/(1 + (−4.9)2 )
x.*abs(x)./(1+x.^2) = −4.8 × | − 4.8|/(1 + (−4.8)2 ) .
..
.
(Of course we should not become overconfident. This rule for dividing by
vectors cannot be used in Mathematics proper.)
Note that p.*q and p*q are entirely different. Even if p and q are matrices
of the same size and both products can be legitimately formed, the results
will be different.
Exercise 13
1. (Easy) Find two 2×2 matrices p and q such that p.*q 6= p*q.
22
Before more exercises, we show how to add further curves to the graph
above. Suppose we want to compare the function we have already drawn,
with the functions x|x|/(5 + x2 ) and x|x|/( 51 + x2 ). This is done by the
following three additional commands. (Remember x already contains the
x–values used in the plot. These new commands are most easily entered by
editing previous lines.)
y2 = x .* abs(x) ./ (5 + x.^2) ;
y3 = x .* abs(x) ./ ( 1/5 + x.^2) ;
plot2d(x,[y y2 y3])
Exercise 14
1. Use Scilab to graph the functions cos(x), 1/(1 + cos2 (x)), and 1/(3 +
cos(1/(1 + x2 )) on separate graphs.
sin(x)
lim = 1.
x→0 x
(Hint: Select a suitable range and a set of x values and plot sin(x)/x. If
you get messages about dividing by zero, it means you tried to evaluate
sin(x)/x when x is exactly 0.)
Bring the plot window to the front. The title should appear on the graph.
If everything is okay, click on the ‘file’ menu → ‘print scilab’ item in the
graph window. If everything is set up correctly, the graph will appear on the
printer attached to your computer.
After printing a graph, it is useful to take a pen and label the axes (if
that was not done in Scilab), and perhaps explain the various points or
23
curves in the space underneath. Alternatively before printing the graph, use
the Scilab command xtitle with two optional arguments and the legend
argument of the plot2d command for a more professional appearance. For
instance
xbasc()
plot2d(x,[y y2 y3],leg=’function y@function y2@function y3’)
xtitle(’Plot of three functions’,’x label’,’y label’)
Another option is to use the graphics window file menu item, export, or
the xbasimp command to print the current graph to a file so that it can be
printed later. For example to produce a postscript file use the command
xbasimp(0,’mygraph.eps’)
This will write the current graph (associated with graphics window 0) to the
file mygraph.eps. This file can be stored on your floppy and printed out
later.
• The word processor must be open at the same time as we are using
Scilab.
• Move to the Scilab plot window, and use the file→copy to clip-
board (enhmetafile) menu subcommand. (This copies the current
graph onto the clipboard.)
• Then move to the word processor, place the cursor where graph is to
go, and press ctrl-v to paste the graph into the word processor.
Several graphs can be saved in a file this way and incorporated into the final
report. Ensure though that the report file is saved on your floppy disk or
onto your personal home directory.
If you are working in the computer laboratories, make sure the report file
is small enough to fit on a floppy; and make sure you store the report on the
floppy and take the floppy when you leave.
24
7.5 Saving Graphs
The easiest way to save a graph is to save the Scilab command you used to
create the graph. These are usually only one or two lines. If the commands
are more than one or two lines long, they should probably be saved in a file
(see later chapters.)
25
Index
apropos, 8 - xbasc, 10
argument, 7 - xtitle, 11
plot2d, 11
C, 3 Polynomial evaluation, 20
Create Matrices Polynomial Functions
- diag, 17 - derivat, 20
- ones, 17 - horner, 20
- rand, 17 - poly, 20
- zeros, 17 - roots, 20
datafit, 11 Random Matrices, 17
Determinants Rational Functions, 21
- det, 16 Resources, 4
Eigenvalues Rlab, 3
- spec, 16 Scilab, 3
Eigenvectors Scilab Constants
- bdiag, 16 - %e, 6
Errors, 5 - %i, 7
help, 8 - %pi, 6
Help Functions Scilab Functions
- help, 8 - abs, 7
- menu, 9 - apropos, 8
- atan, 7
Indices, 16 - backslash \, 18
Inverse - bdiag, 16
- inv, 16 - datafit, 11
- derivat, 20
Java, 3 - det, 16
- diag, 17
Linear Equations, 18
- exp, 6
log plots, 14
- help, 8
Matlab, 3 - horner, 20
Matrix Multiplication, 17 - imag, 7
- inv, 16
Octave, 3 - ones, 17
- plot2d, 11
Plot Functions
- poly, 20
- plot2d, 11
26
- rand, 17
- real, 7
- roots, 20
- sin, 6
- spec, 16
- xbasc, 10
- xtitle, 11
- zeros, 17
xtitle, 11
27