Unit 15 Introducing to Scilab
UNIT 15
INTRODUCTION TO SCILAB
Structure Page No.
15.1 Introduction 93
Objectives
15.2 Downloading & Installing Scilab 94
15.3 How to Start Scilab 98
15.4 Scilab Menu Bar 100
15.5 Function using Scilab 102
15.6 Matrices using Scilab 105
15.7 Looping and Branching 112
15.8 Plotting through Scilab 114
15.9 Summary 115
15.1 INTRODUCTION
Scilab is a programming language and has many algorithms available
for numerical computations and scientific computations. Scilab is an
open source application and is an alternative to MATLAB. Here is a list
of features of Scilab:
• It is open source software which can be downloaded and installed
without any restriction and the user does not pay for it.
• Operating systems like Windows, Linux and MAC are used to run
scilab.
• The development processes are faster as Scilab directly uses the
access of high level languages.
Scilab was created in 1990 by researchers of French Institute for
Research in Computer Science and Automation. Initially, it was named
as ψ lab.
This unit provides you an introduction to Scilab. We shall also discuss
some basic operations performed using Scilab such as working with
matrices, functions, plotting functions etc. 93
Block 5 Scilab Manual
And now, we will list the objectives of this unit. After going through the
unit, please read this list again make sure you have achieved the
objectives.
Objectives
After studying this unit you should be able to
• download and install Scilab in WINDOWS
• compute various functions
• perform operations on matrices etc.
• perform numerical computations
• plot 2D graphs
15.2 DOWNLOADING & INSTALLING SCILAB
You can easily download Scilab on different operating systems such as
GNU/Linux platforms, Windows 2007/XP/VISTA platforms, MacOSX
10.5 Intel platforms. Scilab is distributed freely and is available on open
source. Scilab is currently being used in educational and industrial
environments around the world, Scilab includes hundreds of
mathematical functions.
The home page of Scilab is www.scilab.org. Here is the stepwise
procedure for downloading and installing Scilab in WINDOWS.
Step – I: (Downloading the Scilab): Search for download Scilab on
any of the search engine e.g. google, yahoo, etc. You will get the
window in google, given in Fig. 1:
Fig 1: Search Engine results for Scilab
Now select www.scilab.org/download in the window given above and
double click it. You will get the window as shown in Fig. 2:
94 Fig 2: Downloading Scilab
Unit 15 Introducing to Scilab
You are seeing an arrow on which Download Scilab is written.
Double click the arrow. It will start downloading scilab. When the
download is complete you will get the window shown in Fig. 3:
Fig 3: Run exe file
Step – II: (Installing Scilab): Select Run. It will open select start menu
folder where the application to be saved as given in the window of
Fig. 4:
Fig 4: Selecting folder
Click on the button marked Next in the window for select start menu
folder in Fig. 4. It will open scilab setup (Fig. 5):
Fig 5: Setup wizard
Now, you can see the setup wizard in Fig. 5. Click again on Next button. This
will bring up the license agreement window shown in Fig. 6: 95
Block 5 Scilab Manual
Fig 6: License agreement
Accept the terms of the license agreement. Select and press Next after
selecting ‘I accept the agreement’, and get the window as given in
Fig. 7:
Fig 7: Selecting Destination Location
Select designation location gives you an opportunity to select the
desired location for saving the application. You may enter the
destination location and press next. It will take you to window shown in
Fig. 8:
Fig 8: Selecting Components
Here, you see a list of components, from which you can choose
required components or can continue with the default ones. Again press
96 Next to get the window shown in Fig. 9:
Unit 15 Introducing to Scilab
Fig 9: Selecting start menu folder
Once again press Next, you will get a window, which provides you
options to select additional task, if any. You can always select for the
default ones as shown in Fig. 10:
Fig 10: Selecting Additional Tools
After selecting additional tools for additional tasks, select and press
next. You will come across another window ready to install as given in
Fig. 11:
Fig 11: Install Command
Again press Next. This will open installing window as shown in Fig. 12.
Please wait till the installation is complete. 97
Block 5 Scilab Manual
Fig 12: Installing Scilab
You will now see the completing setup wizard window given in Fig. 13
with message to click finish to exit setup.
Fig 13: Completion of Installation
Press finish now. Scilab has been downloaded and the installation
procedure is complete.
You will see the Scilab shortcut icon on the desktop as shown in
Fig. 14.
Fig. 14 Shortcut icon of the Scilab
Now, you have successfully installed Scilab but later we shall be adding a
toolbox called SIVP, which will be discussed in unit 16.
Next we shall see how to start Scilab.
15.3 HOW TO START SCILAB
There are several ways in which the Scilab can be used. For example,
98 Scilab can be started using the console window of Scilab in an
Unit 15 Introducing to Scilab
interactive mode. You can also start Scilab by using the exec function
against a file. Scilab can also be started by using batch processing. You
can start Scilab by any of the listed method. In this unit, we are going to
starting Scilab by using the console window.
In console window, commands are typed, results are analysed and
process is continued till the final form of the output in terms of result is
computed.
To start Scilab, double click on the shortcut of the Scilab icon and
launch the Scilab window which is called console window, as shown in
Fig. 15. You will enter Scilab commands at the prompt (-->).
Fig 15: Starting with Scilab
So far we have discussed installation of Scilab and starting Scilab. Let us now
discuss the commands to be used in Scilab. Scilab can be used as a simple
calculator to perform numerical computations. It also has the ability to define
variables and store values in them so that they can be used later.
Let us demonstrate some examples.
Example 1: Type x = 1 followed by Enter key, followed by y = 2 followed by
Enter key, followed by x*y. On the Scilab window, the commands would
appear as follows. You can also see that the result 2, is displayed by Scilab.
─ → x = 1 [Create and set a real variable x to 1]
x =
1
─ → y = 2 [Create and set a real variable y to 2]
x =
1
─ → z = x*y [Performing multiplication on variables]
z =
2
Example 2: ─ → 2 + 3
ans =
5.
─ → 2/3
ans =
.666667
─ → 2^3 99
Block 5 Scilab Manual
ans =
8.
It may be noted here that Scilab creates a variables named “ans”to
store results of calculations whenever we do not supply a variable for
this.
Here is a list of some elementary mathematical operators:
Table 1: Some Mathematical Operators
Operations Symbol used for
Addition +
Subtraction -
Multiplication *
Division /
Power Transpose
^
Conjugate ,
We have so far been discussing examples where Scilab is used to
compute numbers. Scilab can manage different kind of data, digital
images, etc. In the unit 16, we shall discuss how to analyse an image.
As you know, a digital image is an array of numbers represented in a
matrix. In fact, every digital object, text, images, sound, video or
software ultimately boil down to numbers, to be specific, zeros and
ones.
Now we discuss some very basic features of the Scilab environment
which are helpful in working with Scilab effectively and efficiently.
• In Scilab, a command line is entered by typing after the prompt or by
copying it from other windows to the prompt in the Scilab window.
• To delete characters of a command, we use backspace.
• We can also use left and right arrow keys to move back and forth
along the command and insert (by typing) or delete (by using the
delete key) specific characters.
• The Up and Down arrow keys help us move back and forth among
previous commands of the current session, enabling command
history management.
• We can enter more than one command on the same line by
separating the commands by semicolons (;).
For example, ─ → a = 5; b = 2.
In addition, the following key shortcuts are also supported by Scilab:
• Ctrl-a move to beginning of line
• Ctrl-b move backward one character
• Ctrl-c interrupts Scilab and pause after carriage return.
Clicking on the Control/stop button enters a Ctrl-c.
100 • Ctrl-d delete one character (at cursor)
Unit 15 Introducing to Scilab
• Ctrl-e move to end of line
• Ctrl-f move forward one character
• Ctrl-h delete previous character
• Ctrl-k delete to the end of the line
• Ctrl-n recall next line
• Ctrl-p recall previous line
• Ctrl-u cancel current line
• Ctrl-y yank the text previously deleted
Now in the following section, we shall discuss Scilab menu bar.
15.4 SCILAB MENU BAR
The scilab window always displays a menu bar with the following
menus: file, Edit, control, applications, ? and toolbox. Let us see the
features available in these.
File Menu
The file menu has the following menu options which are self-
explanatory. These are identical to File menus in most other generic
application software as shown in Fig. 16:
Fig 16: The File menu
Edit Menu
The common edit options like Cut, Coy, Paste, and Empty/Clipboard &
Select all are available in this menu. The list of edit menu is given in
Fig.17.
Fig 17: The Edit menu
Control Menu
The control menu includes Interrupt, which interrupts execution of
Scilab and enters in pause mode; Resume, continues execution after a
pause entered as a command in function or generated by the Stop
button or Control C and Abort, which aborts execution after one (or
several) pause, and returns to top-level prompt. All these are shown in
Fig. 18: 101
Block 5 Scilab Manual
Fig 18: The Control menu
Applications Menu
We can use Editor, Scicos, Matlab to Scilab translator or Variable Editor
in the Applications menu as shown in Fig. 19:
Fig 19: The Applications menu
? Menu
This menu presents interesting option Scilab Demonstrations. Selecting
this will displays a large number of demos in various areas which are
very useful for the beginners. The list of demos is shown in Fig. 20. The
required demo can be selected and viewed.
Fig 20: The ? menu
Toolboxes
Tool boxes are a collection of specialized commands/functions catering
to specific area. To use any tool box, it has to be downloaded and
installed. See the following screenshot of Scilab with SIVP installed.
The tool box can be launched by clicking on the menu option in the
Toolbox Menu.
In the following sections, we shall discuss various other functions and
their operations done in Scilab.
15.5 FUNCTION USING SCILAB
Before we start discussion on various functions, let us discuss about
name of the variable.
Variable name can be as long as you want. Scilab is case sensitive,
therefore upper and lower case letters are considered differently. For
102 example N and n are two different variables.
Unit 15 Introducing to Scilab
If any comment is to be added which is to be ignored while processing,
it is started with “//”.
For example
--> // this is example.
Scilab uses the following inbuilt mathematical functions:
sin cos tan cot cosec sec
sinh cosh tanh coth cosech sech
exp log log 10 log 2 log m max
min modulo sign sqrt
Let us now discuss few examples on these:
For example:
Example 3: ─ → x = sin (2)
x =
0.9092974
─ → y = cos (2)
y =
- 0.4161468
─ → x^2 + y^2
ans =
1.
Complex numbers are stored in pairs of floating point numbers. The
pre-defined variable % i represents the imaginary number i for which
i2 = −1.
For example,
─ → x = 2 + % i
x =
1 + i
Complex numbers are shown by following functions:
Real part real
Imaginary part imag
Multiplicating by i imult
Strings can be stored in variables. In the following example you will
understand it.
For example,
Example 4: ─ → x = “string”
x =
string
103
Block 5 Scilab Manual
Example 5: (Concatenation)
─ → x = “tool”
x =
tool
─ → y = “box”
x =
box
─ → x + y
ans =
toolbox
Again, you may note that, ans variable has been used whenever we
make a computation and do not store the result into an output variable.
To define a new function, we use the function and endfunction which
are Scilab keywords. Let us take an example by defining a new function
named myfunction, which takes the input argument x, multiplies it by 2,
and returns the value in the output argument y.
function y = myfunction ( x )
y = 2 * x
endfunction
The statement function y = myfunction (x) is the header of the
function while the body of the function is made of the statement y = 2 *
x. The body of a function may contain one, two or more statements.
There are at least three possibilities to define the previous function in Scilab.
• The first solution is to type the script directly into the console in an
interactive mode. Notice that, once the “function y = myfunction (x)”
statement has been written and the enter key is typed in, Scilab creates a
new line in the consle, waiting for the body of the function. When the
“endfunction” statement is typed in the console, Scilab returns back to its
normal edition mode.
• Another solution is available when the source code of the function is
provided in a file. This is the most common case, since functions are
generally quite long and complicated. We can simply copy and paste the
function definition into the console. When the function definition is short
(typically, a dozen lines of source code), this way is very convenient. With
the editor, this is very easy, thanks to the Load into Scilab feature.
• We can also use the exec function. Let us consider a Windows system
where the previous function is written in the file “C: \myscripts\examples-
functions. sce". The following example shows the use of exec to load the
previous function.
-→exec (“C: \myscripts\examples-functions. sce")
-→function y = myfunction ( x )
-→ y = 2 * x
104 -→endfunction
Unit 15 Introducing to Scilab
Now, let us discuss the operations on matrices.
15.6 MATRICES USING SCILAB
Matrices play a central role in image processing. The basic data type is
the matrix which requires the number of rows, the number of columns,
the type of data.The data type can be real, integer, boolean, string or
polynomial. When two matrices have the same number of rows and
columns, we say that the two matrices have the same shape.
Matrix operations that are built-in into Scilab are addition, subtraction,
multiplication, transpose, inversion, determinant, logarithmic,
exponential and many others.
There is a simple and efficient syntax to create a matrix with given
values. The following is the list of symbols used to define a matrix.
* square brackets “[“and”]” mark the beginning and the end of the
matrix,
* commas ” ,” separate the values in different columns,
* semicolons “ ; ” separate the values of different rows.
The following syntax can be used to define a matrix, where blank
spaces are optional (but make the line easier to read) and “ … ”
denotes intermediate values:
A = [a11, a12, …, a1n; a21, a22, …, a2n; …; an1, an2,
…, ann].
For example, we create a 2 × 3 matrix of real values.
-→A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A =
1 2 3
4 5 6
7 8 9
Several Scilab commands allow to create matrices from a given size,
i.e. from a given number of rows and columns. The most commonly
used are eye, zeros and ones. The identity matrix is represented by eye.
These commands take two input arguments, the number of rows and
the number of columns.
The matrix with each element 1 is represented by the function ones.
For example,
-→A = ones (2, 4)
A =
1. 1. 1. 1.
1. 1. 1. 1. 105
Block 5 Scilab Manual
The identify matrix is represented by eye.
For example,
-→A = eye (3, 3)
A =
1 0 0
0 1 0
0 0 1
A diagonal matrix can be created as follows:
-→d = eye (3,3) * 5,
-→d =
5 0 0
0 5 0
0 0 5
The zero matrix: A zero matrix can be created by using zeros.
-→A = zeros (3,4)
A =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Similarly ones function creates the matrix with all elements being 1. For
example,
-→A = ones (2, 3)
A =
1. 1. 1.
1. 1. 1.
The size function returns the number of rows or the number of columns
of a matrix.
nr = size (A , sel)
where, sel has to be given values:
• sel =1 or sel =”r”, returns the number of rows,
• sel =2 or sel =”c”, returns the number of columns.
• sel =”*”, returns the total number of elements, that is, the number
of columns times the number of rows.
We use the size function in order to compute the total number of
elements of a matrix.
106
Unit 15 Introducing to Scilab
For example, -→ size (A, “*”)
ans =
6.
Transpose of a matrix is shown by ’.
For example,
-→ a = [ 1, 2, 3; 4, 5, 6]
-→ b = a’;
-→ b =
1 4
2 5
3 6
Operations in matrices are done in the following way:
• a + b adds a to b provided a and b are of same size.
• a - b gives subtraction of b from a, if both a and b are of same size.
• a * b give product of two matrices a and b, if they are computable to
multiply.
• inv (a) inverts matrix a, if a is positive definite. A warning is
displayed is not.
• det (a) gives determinant of matrix a, provided a is a square matrix.
• log (a) returns a matrix, where each element is log of the
corresponding element of matrix a.
• a. * b gives element by element multiplication.
• a^2 gives a * a, if a is square matrix.
• a.^2 gives element by element square.
There are several methods to access the elements of a matrix A:
• the whole matrix, with the A syntax
• element by element with the A(i , j) syntax,
• a range of index values with the colon “:” operator.
Now let us demonstrate by taking a few examples:
Example 6: -→A = ones (2, 3)
A =
1. 1. 1.
1. 1. 1.
-→B = 2 * ones (2, 3)
B =
2. 2. 2.
2. 2. 2.
-→A+B 107
Block 5 Scilab Manual
ans =
3. 3. 3.
3. 3. 3.
Example 7: -→A = ones (2, 3)
A =
1. 1. 1.
1. 1. 1.
-→A (1,1)
ans =
1.
-→A (12,1)
!—error 21
Invalid index
-→A (0,1)
!—error 21
Invalid index.
Example 8: -→A = ones (3, 3)
A =
1. 1. 1.
1. 1. 1.
1. 1. 1.
-→B = A + 3*eye()
B =
4. 1. 1.
1. 4. 1.
1. 1. 4.
Example 9: -→A = ones (2, 2)
A =
1. 1.
1. 1.
-→B = eye (A)
B =
1. 0.
0. 1.
Example 10: -→A = [1 2
-→3 4]
A =
1. 2.
3. 4.
108 -→B = [5 6
Unit 15 Introducing to Scilab
-→7 8]
B =
5. 6.
7. 8.
-→A + B
ans =
6. 8.
10. 12.
Example 11: -→A = [1 2
-→3 4]
A =
1. 2.
3. 4.
-→A + 1
ans =
2. 3.
4. 5.
Example 12: -→A = [1 2
-→3 4]
A =
1. 2.
3. 4.
-→A + 1
ans =
2. 3.
4. 5.
The addition is possible only if the two matrices are conformable to
addition. In the following session, we try to add a 2 × 3 matrix with a 2× 2
matrix and check that this is not possible.
Example 13: -→A = [1 2
-→3 4]
A =
1. 2.
3. 4.
-→B = [1 2 3
-→4 5 6]
B =
1. 2. 3.
4. 5. 6.
-→A + B 109
Block 5 Scilab Manual
! -- error 8
Inconsistent addition.
In the following example, an unsymetric matrix of doubles containing
complex values is used, so that the difference between the two
operators is obvious.
Example 14: -→A = [1 2; 3 4] + %i * [5 6; 7 8]
A =
1. + 5 .i 2. + 6 .i
3. + 7 .i 4. + 8. I
-→A ’
ans =
1. – 5. i 3. – 7. i
2. – 6. i 4. – 8. i
-→A ’
ans =
1. + 5. i 3. + 7. i
2. + 6. i 4. + 8. i
In the following example, we define an unsymetric matrix of doubles
containing real values and see that the results of the “ ‘ “ and “ . ‘ “ are
the same in this particular case.
Example 15: -→B = [1 2; 3 4]
B =
1. 2.
3. 4.
-→B ‘
ans =
1. 2.
3. 4.
-→B . ‘
ans =
1. 3.
2. 4.
In the following example, we multiply the column vector u by the row
vector v and store the result in the variable A.
Example 16: -→u = [1
-→2
-→3]
u =
1.
2.
110 3.
Unit 15 Introducing to Scilab
-→v = [4 5 6]
v =
4. 5. 6.
-→u*v
ans =
4. 5. 6.
8. 10. 12.
12. 15. 18.
In the following Scilab example, we create a matrix A and test if
elements are more than 3 or less than 3.
Example 17: -→A = [1 2 7
-→6 9 8]
A =
1. 2. 7.
6. 9. 8.
-→A>3
ans =
F F T
T T T
-→B = [4 5 6
-→7 8 9]
B =
4. 5. 6.
7. 8. 9.
-→A>B
ans =
F F T
F T F
-→or (A>B, “r”)
ans =
F T T
In Scilab, it is possible to generate a vector given a range of numbers.
• a = [ 1: 6] creates a vector with 6 elements as follows:
[ 1, 2, 3, 4, 5, 6]
• b = [ 0:0. 5:5] creates a vector with 11 elements as follows:
[0, 0.5, 1.0, 1.5, …..4.5, 5.0].
• r and (4, 5) * 100 generates elements are generated as random
numbers.
111
Block 5 Scilab Manual
In the following section, we shall discuss looping and branching.
15.7 LOOPING AND BRANCHING
In this section, we describe how to write conditional statements.
The if statement
The if statement allows to perform a statement if a condition is
satisfied. In the following script, we display the string “Hello!” if the
condition %t, which is always true, is satisfied.
If ( %t ) then
disp (“Hello !”)
end
The previous script produces:
“Hello!”
If the condition is not satisfied, the else statement allows to perform an
alternative statement, as in the following script.
If ( %t ) then
disp (“Hello !”)
else
disp(“Goodbye !”)
end
The previous script produces:
Goodbye !
In order to get a boolean, any comparison operator can be used, e.g.
“==”, “>”, etc… or any function which returns a boolean.
In the following example, we use the “==” operator to display the
message “Hello !”.
For example,
i = 2
if ( i ==2 ) then
disp (“Hello !”)
else
disp (“Goodbye !”)
end
The Select Statement
In the following script, we want to display a string which corresponds to
112 the given integer i.
Unit 15 Introducing to Scilab
For example,
i = 2
select i
case 1
disp (“One”)
case 2
disp (“Two”)
case 3
disp (“Three”)
else
disp (“Other”)
end
The for statement
The for statement allows to perform loops, i.e. allows to perform a
given action several times.
For example: In the following Scilab script, we display the value of i,
from 1 to 5.
for i = 1 : 5
disp (i)
end
The while statement
The while statement allows to perform a loop as long as a boolean
expression is true.
In the following script, we compute the sum of the numbers i from 1 to
10 with a while statement.
For example:
s = 0
i = 1
while ( i<= 10 )
s = s + i
i = i + 1
end
At the end of the algorithm, the values of the variables i and s are:
s =
55.
i =
11. 113
Block 5 Scilab Manual
In the next section we show how plotting can be done in Scilab.
15.8 PLOTTING THROUGH SCILAB
Let us learn to plot simple graphs. We first have to generate the data to
be used for the graph. Let us assume we want to draw the graph of cos
(x) and sin (x) for one full cycle ( 2 π radius). Let us first generate the
values for the x-axis with the following command:
-→x = [0 : % pi/16:2 * % pi];
In the above command, % pi is a predefined constant representing the
value of π . The command requires a start value, an increment and an
end value, which are 0, π / 16 and 2 π respectively in the above example.
Increment is optimal. If not given, it takes default value 1.
Now let us create the value for y-axis.
-→y = [ cos (x) sin (x)];
For plotting these, we use
-→plot 2d (x,y)
Scilab can create x-y plots with the plot function, contour plots with the
contour function, 3D plots with the surf function, histograms with the
histplot function and many other types of plots.
In order to get an example of a 3D plot, we can simply type the
statement surf () in the Scilab console.
-→surf ()
The various functions used to plot are given below:
plot 2D plot
surf 3D plot
contour contour plot
pie pie chart
histplot histogram
bar bar chart
Let us see simple instances such as plot (x,y) which plots the variable x
against y, with default graphic settings.
-->x=[10, 12, 14, 16, 19]
x =
10. 12. 14. 16. 19.
-->y=[1, 2, 3, 4, 5]
y =
1. 2. 3. 4. 5.
-->plot 2d(y,x)
114
Unit 15 Introducing to Scilab
Let us see the output of the plot in the following Fig. 21.
Fig. 21: Plotting (y,x)
You may note that the window title bar displays “Scilab Graphic number
(0)”. Scilab can open up 20 such windows at the same time.
Let us see more examples.
Example 18: Plotting sine function.
-->x=[0: 0.1: 6.28];
-->plot2d(sin(x))
The output is shown in Fig.22.
Fig. 22: Sine Function
Now let us summaries what we have studied in this unit.
15.9 SUMMARY
In this unit we have discussed following points:
1. The applications of Scilab.
2. Installation of Scilab.
3. Getting started with Scilab. 115
Block 5 Scilab Manual
4. Basic command of Scilab.
5. Menu bar and Tool box of Scilab.
6. Functions and their operations using Scilab.
7. Matrix operations and its operations through Scilab.
8. How to write conditional statements using looping and branching.
9. Plotting of 2D figures through Scilab.
116