You are on page 1of 8

ICS Summer School on Biomathematics and Bioinformatics

Tutorial Scilab

By A. Blouza & L. El Alaoui

July 16th August 10th , Roscoff, 2012

Scilab is a free software mainly developed at INRIA (Institut National de Recherche en Informatique
et Automatique). You can download it at http://www.scilab.org. Its a cross-platform : Unix/Lunix,
Mac OS X, and even Windows, in various flavors. It uses a proper programming langage and does not
need any compilation step. Scilab has many programmed functions as well as graphics tools.
The aims of the first workshop are :

The presentation of Scilab.

An introduction to programming with Scilab : getting started.

1 First use of Scilab

Exercise 1. Write the successive instructions below in the commande window.

2+2
a=1/3;
format(), a
format(v,15), a // 12 digits!
(1-%i)^2
eps, 1+%eps
A=[1,2;3,4];
A
A*[2,3;1,1] // matrices product
sin([%pi,%pi/2])
z=1:4;
z

Let us note that the semicolon, when added, at the end of the line enables to cancel the display results.
The double slash // delimitates, on the left, a comment or explanation line.

2 Programming with Scilab

Scilab has a programming langage which is different from others langages such as C, C++ or Fortran
by the fact that there is no variable declaration. Scilab programming instructions have a block structure :
a key word to begin (if, for...) and end for closing.

1
1) Loops. There are two types of loops. The loop for and the loop while.
a) The loop for enable to execute successive instructions. Its syntax is :
for
variable=expression
instruction, ... , instruction
end
If expression is a matrix or a row vector, variable takes as values the values of each column of
the matrix.
If expression is a list, variable takes as values the successive entries of the list.
Examples :
sum=0; // initialisation
for i=1:10 // i takes integer values in {1,..., 10}
sum=sum+i; // At each iteration, the integer i is added to sum
end
At the end of that loop, the integer sum gives the summation of the 10 first integers.
The set of indices can also be given in a vector :
for i=[2 4 7 10] // i takes successive values 2, 4, 7 and 10
Intructions block
end
b) The loop while enable to execute some instructions while given conditions are satisfied. The loop
below enables to compute the 10 first integers sum.
i=0;
sum=0;
while i<=10
i=i+1;
sum=sum+i;
end
2) Conditionnal instructions. There are two types. : if then else and select case.
a) Example of instructions if then else to compute the absolute value x.
x=3.1;
if x<0 then
y=-x
else
y=x
end
We can also add others tets with the instruction elseif. In such a case instructions are on the
form :
if test1
sequence of instructions 1
elseif test2
sequence of instructions 2
else
sequence of instructions 3
end
b) In the case of many tests, instructions select case are used.
select num
case 1 y = case 1
case 2 y = case 2
else y = other cases
end

2
3) Scilab logic operators.
& | e == <> < > <= >=
and or no equal different less to larger than less or equal to larger or equal to

3 How to excute a Scilab script ?

To execute a long or complex sequence of instructions, it is preferable to write it before in a script


(with .sce scilab extension) instead of writing it in the command window.
Exercise 2. a. Create a directory and place in it.
b. Open the scilab editor and create a file called test.sce containing the instructions below :
A=rand(4,4); B=inv(A);
C=A*B
You can run the script test.sce :
i) with the editor of scilab, using the Execute option,
ii) or in the command scilab window, by exec(test.sce).

4 Functions with Scilab

It is possible to construct new mathematical functions with Scilab. Functions take different forms
with different types of input arguments (scalar, matrix,...)
Exercise 3. With scilab editor, create a file called function.sce and containing the following instructions :

function [c]=fct(n)
if (n<0) | (int(n)<>n)
c=0;
else
c=1;
for i=1:n
c=c*i;
end
end
endfunction

Download this function and run it with different values. What function is it ?
Exercise 4. Write a function which gives, as output argument, the maximum of two real values.

5 Online help of Scilab

Exercise 5. Find, using Help of scilab, functions that


a. return the identity matrix, the null matrix, a matrix with all coefficients equal to 1.
b. Compute the eigenvalues of a matrix.
c. Compute the time execution of a job.
Exercise 6. Rewrite the function of the exercise 3 using the Scilab command prod.

3
6 Vectors
1) A vector can be constructed in different ways. We list below some of them.
a) when the vector size is small, one may write v=[1,2] for a row vector and v=[1 ;2] for a column
vector ;
b) when the vector components follow an arithmetical progression one may write v=2 :0.1 :3 or
v=linspace(2,3,11) ;
c) on initializing the vector, then performing a loop on the index one may do the allocation v(i)=2 ;
d) on initializing the vector v with the empty vector : v=[], then by concatenating in a loop each
element with an allocation of the form v=[v,2] ;
e) on performing sums (instruction +), multiplications (instruction .*) and divisions (instruction ./)
terms by terms from simple vectors.
2) The size of a vector v and its length can be obtained with the commands size(v) and lenght(v) respec-
tively. The ith component of a vector v is given by v(i).
Exercise 7. Construct in three different ways, the row vector that components are the square of the 50
first integers.

7 Manipulation of matrices

For Scilab, each variable is a particular case of matrices of size m n, so the construction of a matrix
is performed in the manner as that of a vector.
1) Here, we list some examples of matrix construction.
a) when the matrix size is small one may write A=[1,2,3 ;3,4,5] for a matrix of size 2 3 ;
b) on initializing the matrix A, and then owing a double loop on the indices one proceed to the
allocation A(i,j)=2 ;
c) on initializing the matrix A with a row (or column) vector, then by concatenating in a loop each
row (or column) with an allocation of the form A=[A ;v] (respectively A=[A,v]). Note that this
method is also valid for the matrix concatenation ;
d) on performing sums (instruction +), multiplications (instruction .*) and divisions (instruction ./)
terms by terms from simple matrices.
2) The size of A is given by size(A), the coefficient aij at row i and column j of A is given by A(i,j) and
the ith row and the jth column are given by A(i, :) (A( :,j)) respectively.
Exercise 8. Construct in two different ways the matrix 10 10 giving the results of the multiplication
table.

8 Plot

For drawing a graph, Scilab has several commands especially the instruction plot. Below, some
examples.

x=linspace(0,4,100)
y=x.^2
z=cos(x)
plot(x,y)
plot(z,y)

4
A graph window can be expunged thanks to the command clf. One can also draw two graphs in the same
window with the command plot(x,y,x,z), add a legend legend(The cosinus function cos(x)) and a title
xtitle(My first plot).

Exercise 9. On using the help, write the script graph.sci allowing to plot the functions g : x 7 cos(x2 +
3x 1), h : x 7 sin(x2 + 3x 1) and p : x 7 x2 + 3x 1 on [2, 2]. The script must reproduced exactly
the figure 1.
.

Graphes de f, g et p

10

g(x)=cos(x^2+3x1)

8 h(x)=sin(x^2+1)

p(x)=x^2+2x1

4
y

4
2.0 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0
x

Figure 1 Figure obtained with graph.sci

9 Solving linear system

Exercise 10. 1. For solving system in an upper triangular form one may use the following function :
function u=upper(A,b)
[n,m]=size(A);
u=zeros(n,1);
u(n)=b(n)/A(n,n);
for j=n-1:-1:1,
u(j)=(b(j)-A(j,,j+1:n)*u(j+1:n))/A(j,j);
end
endfunction
Use this function on examples with matrices of size n n and vectors of size n are randomly
generated (n 100). Compare the results and the computational time with those obtained from
the instruction linsolve.
2. Write a function fctgauss for applying the Gauss method to the linear system Au = b.
3. Write a function solvegauss for solving with the Gauss method the linear system Au = b.

5
10 Condition number

The influence of rounding errors on the accuracy of the result of the solution of the linear system
Ax = b, with A invertible, can be quantified by the condition number which is defined by :

Condp (A) = ||A||p ||A1 ||p

where
||Ax||p
||A||p = sup ,
xCn ,x6=0 ||x||p
denotes the subordinate norm to the vector norm.

It is therefore essential to estimate this value before solving a linear system by a computational
software such as Scilab (even with an exact method, as the Gauss method). To compute this number
with Scilab one can use the command cond.
Exercise 11. Consider the linear system : Ax = b where

10 7 8 7 x1 32
7 5 6 5 x2 23
A= 8
, x = et b=
6 10 9 x3 33
7 5 9 10 x4 31

1. Compute the eigenvalues of A.


2. Compute the condition number of A, Cond2 (A).
3. Compute the solution x with linsolve.
4. (Perturbation of the right hand side) Compute the solution x of Ax = b + b when b = 0.01
rand(1, 4) . Show that the relative error on the solution is due to the amplification of the relative
error on the right hand side by the condition number :

||x x||2 ||b||2


Cond2 (A) .
||x||2 ||b||2

5. (Perturbation of the matrix coefficients) Let B be a pertubation of A defined by B = A + 0.01


rand(4, 4).
6. Compute the spectrum of B. What are the eigenvalues of A changed most ?
7. Compute the solution x of (A + A)x = b, when

0 0 0.1 0.2
0.08 0.04 0 0
A =
.

0 0.02 0.11 0
0.01 0.01 0 0.02

Prove that
||x x||2 ||A||2
Cond2 (A) .
||x||2 ||A||2
Consider the following linear system
    
1.2969 0.8648 x1 0.8642
=
0.2161 0.1441 x2 0.144

How accurately should we know the right hand side of the system to avoid the spreading of the
errors ?

6
11 Solving system ordinary differential equations (ODE)

11.1 Basic use of ode

The instruction ode allows to solve approximatevely a Cauchy problem on a given interval. The right hand
side of the ODE y = f (t, y) is an input argument defined as a function of the two variables t (real) and y
(vector). Note that even if f does not depend on the time t this definition must be used.

function [f]=rhs(t,y)
Instructions block defining the components of f in respect of t and y
endfunction

Before any study of differential equation, it is prudent to ensure that the Cauchy problem is well conditionned.
The examples below highlight the value of such a precaution.
Exercise 12. Apply the Euler explicit method for solving the following ODE :
y = 3y 1, y(0) = 1/3 on [0, 30] with y0 = 0.3333333333,
and
y = 150y + 30, y(0) = 1/5 on [0, 1].
For each equation compare the results with the exact values of y at t = 30 and t = 1 respectively.
Exercise 13. Consider the so-called Van der Pol second order differential equation :
y = 0.4(1 y 2 )y y.
Write a function that defines the right hand side of the above equation. Then, use the instruction ode for
solving this equation on the time interval [0, 2] with given initial conditions y(0) and y (0).

11.2 Phase plane

A phase plane is a visual display of some characteristics of differential equations. Phase planes are useful in
visualizing the behavior of physical systems ; in particular, of oscillatory systems such as predator-prey models
(see Lotka-Volterra equations below). These models can spiral in towards zero, spiral out towards infinity,
or reach neutrally stable situations called centres where the path traced out can be either circular, elliptical, or
ovoid, or some variant thereof. This is useful in determining if the dynamics are stable or not. multiple steps,
some of which involve dynamic equilibria rather than reactions that go to completion. In such cases one can
model the rise and fall of reactant and product concentration (or mass, or amount of substance) with the
correct differential equations and a good understanding of chemical kinetics. dimensions qui sont laltitude y
et la vitesse y . Dans le cas ou lespace des phases est un plan, on peut obtenir une idee de la dynamique en
dessinant simplement le champ de vecteurs dans un rectangle [xmin , xmax ] [ymin , ymax ] avec linstruction
graphique fchamp dont la syntaxe est : The graphic instruction of Scilab fchamp is used to draw the direction
field of a 2D first order ODE defined by the external function. its syntax is : fchamp(righthandside,t,x,y) where
t is the selected time and x and y are two row vectors which define the grid on which the direction field is
computed.
Exercise 14. Draw the direction field associated to Van Der Pol equation.
Exercise 15. (Dynamical population) by using the instruction ode, solve on the interval [0, 25] the
dynamical Lokta-Volterra system 
x (t) = xy/2 x/2
y (t) = xy + y

7
where we denote by x(t) the predator density and y(t) the prey density and set x(0) = y(0) = 2 the
initial data.

a. Plot the solution (x, y) in the same graphic window.


b. Draw the direction field associated to the Lokta-Volterra system.
c. Do the Lokta-Volterra system has fixed points ? What about their stability ?
d. Verify numerically the qualititative properties of the solution (bounded, nonnegative and periodic
solution).

You might also like