You are on page 1of 38

Introduction to Scilab1

1.1 What is Scilab


If you are already familiar with the software package known as Matlab and
you are also aware of the free software movement, then it is easy to answer
the question “ What is Scilab? ” – Scilab is a free software alternative to
Matlab. For the sake of readers who may be unfamiliar with either or both of
Matlab and free softwares, we present in this chapter a brief introduction of
the same. However, the reader may also skip this chapter in the first reading
and begin with the second chapter, and gain a first hand understanding of
Scilab.

1.2 Matlab®
Matlab, believed to be used by over a million users in industry and academia,
appeared in late 1970s and has become a hot favourite of users who are
either not skilled or simply uninterested in getting entangled with syntax of
languages like C or Pascal, even to solve simple problems. Matlab is hailed
as the language of technical computing and often described as a “Quick and
Dirty” programming language. The interpreted nature makes it “quick” and
the “dirty” part indicates its flexibility of syntax, which programming
puritans might not agree with. Formally, Matlab is a numerical computing
environment and fourth generation programming language. It is developed
by The MathWorks. Among Mathlab’s capabilities, the key is matrix manipulation
(the name Matlab itself is an acronymn of Matrix Laboratory), handling of functions and data,
implementation of algorithms and creation of user interfaces. Matlab is well known for the many
tool boxes (specialized collection of commands and features which can be added on to basic
Matlab), in specialized areas of science, technology, mathematics, statistics etc. Release 7.8 is in
vogue in 2009.

Matlab is a proprietary software and a licence fee is mandatory for its use. The tool boxes are
optional and each comes under its own licence fee. As we will see in the next section, the free
software movement attempts to offer technically, ethically superior and free alternatives to
proprietary softwares. There are many free open source alternatives to Matlab, in particular
GNU Octave, FreeMat, and Scilab. They attempt to be compatible with the Matlab language.
The statistical language S also can be considered in this category as it treats arrays as basic
entities. The open source language R is an implementation of S.

1.3 Free Software

Wikipaedia defines free software as follows; “Free software or software libre


is software that can be used, studied, and modified without restriction, and
1
These notes are extracted from a draft of a book under preparation and should not be circulated. Feedback
on errors, readability etc will be greatly appreciated. Pls email hemaachuth@gmail.com

1
which can be copied and redistributed in modified or unmodified form either
without restriction, or with minimal restrictions only to ensure that further
recipients can also do these things and that manufacturers of consumer-
facing hardware allow user modifications to their hardware. Free software is
available gratis (free of charge) in most cases”. Free software ideas originated from
Richard Stallman who conceived the free software movement in 1983. The Free Software
Foundation was founded soon after to advance Stallman’s free software ideas. It may be noted
that there are currently alternative terms for free software such as "software libre", "Free and
Open Source Software" ("FOSS") and "Free, Libre and Open Source Software" ("FLOSS").

A free software generally permits 4 kinds of freedom to its users:

• The freedom to run the software anywhere, anyway


• The freedom to copy and distribute
• The freedom of access to the source code of the software
• The freedom to modify and redistribute

The flagship of the free software movement is Linux, the free operating system that has made
giant strides in the recent past. There are of course a large number of softwares ranging from
server softwares to tiny utilities that have proven the strength of free softwares, such as:

• MySQL relational database;


• Apache web server
• GIMP raster drawing and image editor;
• OpenOffice.org office suite
• TeX and LaTeX scientific typesetting packages
• Mozilla Web Browser

You can see an exhaustive and growing list of free softwares at the Free Software Directory at
directory.fsf.org.

1.4 History of Scilab

The following is the brief history of Scilab, as summarized in the


Scilab’s official website:

In the 80’s, a CACSD (Computer Aided Control System Design)


software was created at the IRIA (“Institut de Recherche en
Informatique”) at Rocquencourt in France. It was inspired by the
Matlab fortran software from Cleve Moler who founded “The
MathWorks” company later with John Little. Blaise was mainly
developed by François Delebecque and Serge Steer and its purpose
was to have a tool for Researchers in Automatic Control.

Then Blaise became Basile and was sold during a few years by

2
Simulog, the first subsidiary company of INRIA (“Institut National de
Recherche en Informatique et Automatique”).

At the beginning of the 90’s, Simulog stopped selling Basile, and the
software name changed another time to become Scilab. It was then
developed by the Scilab Group composed by six researchers: Jean-
Philippe Chancelier from the ENPC (“École Nationale des Ponts et
Chaussées”), and François Delebecque, Claude Gomez, Maurice
Goursat, Ramine Nikoukhah and Serge Steer from INRIA.

It was then decided to distribute Scilab as free Open Source software.


Scilab 1.1, the first released version of Scilab, was put on anonymous
ftp site on January, 2nd, 1994.

Then the Scilab Group, with the active collaboration of external


developers, developed Scilab until the end of 2002, distributing source
and binary versions of Scilab on the Internet up to Scilab 2.7 version.

At the beginning of 2003, to take in consideration the increased


number of people downloading and using Scilab, and to ensure its
future, development, maintenance, support and promotion, INRIA
decided to create the Scilab Consortium with the support of companies
and academic organizations.

To provide an appropriate response to the sustained growth of the


operation, the Scilab Consortium integrates the Digiteo research
network (2008)

The new organization anticipates an intensification of the resources of


the Consortium with for major objectives to strive for excellence in the
areas considered strategic by its members, to integrate recent
research outcomes, to expand the community of contributors, to
develop a powerful open source ecosystem, and to consolidate the
operation at the European and international level.

However, the Scilab Consortium keeps a privileged link with INRIA as


the Institute remains one of its members, continues to support actively
its development and is also a founder member of Digiteo.

1.5 Downloading & Installing Scilab


Scilab is available for different platforms such as GNU/Linux platforms,
Windows 2003/XP/VISTA platforms, MacOSX 10.5 Intel platforms

3
The home page of Scilab is www.scilab.org. At the time of writing this
book, the latest stable version of Scilab is 5.1.1. You can get the installation
file from www.scilab.org/download/5.1.1/scilab-5.1.1.exe.

A quick taste of Scilab


To enable the reader to get a quick taste of the features of Scilab, we
present in this chapter an informal introduction to a set of hand-picked
commands. Obviously, the treatment is not comprehensive or deep, as the
later chapters attempt to do that. The sequencing of the commands are also
not necessarily logical.

Double click on the Silab icon and launch the Scilab window, as shown
scilab-4.0.lnk
below. We can now start giving Scilab commands.

Fig 2.4 Freshly launched Scilab window

Let us start with some very trivial examples. Type x=5 followed by Enter
key, followed by y=6 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 30, is displayed by Scilab.

4
Fig 2.5 Scilab window displaying results of x*y

There are a few things that may be noted. The syntax of Scilab
commands is very similar to that of C , C++, Java etc. However, there
are no variable declarations, no print statements etc. x*y produces
output, by just suppressing the semicolon after it. Why Scilab is “
quick and dirty” is very evident from this example.

Let us now run through a set of selected examples, with brief


comments on each. The reader is encouraged to work on these
examples in his/her personal computer with a bit of experimentation
too. Here is a minor modification of the first example.

>p=3.7;
>q=6.7;
>ptimesq=p*q;
>2*ptimesq
We can see that Scilab permits the use of identifiers as in C
programming language. Identifiers are variables where values of
mathematical operations are stored. They can be later referred to in a
program as can be seen by the statement 2*ptimesq . The result
49.58 is displayed by Scilab.

Scilab is case-sensitive. See this example.


>a=5;
>a
>A

The reference to a is correctly identified, whereas A produces !--error


4 undefined variable : A

Mathematical operators which are very frequently used and accepted


by Scilab are

5
+ for addition
- for subtraction
* for multiplication
/ for division
^ for power operation

See some illustrations


>2.5+4.75
ans = 7.25

-->3.38+5.49
ans = 8.87

-->5.0-3.75
ans = 1.25

>>8*5.3
ans = 42.4

-->89.34*43.67
ans = 3901.4778

-->24/3
ans = 8.

-->5/2.5
ans = 2.

-->5.0/2.5
ans = 2.

-->5.021/2.5
ans = 2.0084

-->8/5
ans = 1.6

-->8.0/6.0
ans = 1.3333333

-->8.0/5.0
ans = 1.6

-->3^10
ans = 59049.

6
Parenthesis can be liberally used to ensure clarity of what is expected.
>2+3/5
ans = 2.6

-->(2+3)/5
ans = 1.

If you have been typing out the commands we discussed so far, your
Scilab window is possibly cluttered. Use the clear command to clear
the window . You may note that the clear command only changes the
appearance of the window. All variables and their values are intact in
Scilab memory. You may test this by typing ptimesq and verifying
that Scilab returns the original value.

You may also note that commands can not only be corrected using
backspace key while typing , but after the Enter key is pressed, using
the arrow keys we can go to the previous commands , correct and
reuse them. This is convienient in correcting long and cumbersome
commands which have trivial typing mistakes. Of course these are the
classic features of command driven softwares.

On a lighter side, the most important command that one needs to


know with any software package is how to wind up and come out ! . In
Scilab typing exit would take you out of the current session with all
variables and data in memory lost ( There are ways to save them, if
you wish).

As already mentioned, Scilab is a free software alternative to Matlab.


The term
Matlab is an acronym for Matrix Laboratory. Matlab and therefore
Scilab are basically matrix processing softwares. A matrix , in layman’s
language is tabular data many times arranged in rows and columns.
Let us see how Scilab operates simple row matrix, also known as
vector.

Consider the marks scored by 5 students in an examination. These


marks when written in a sequence separated by commas is known as
a vector. Scilab can define a vector mark as follows

-->m= [35, 45, 65, 79, 23]


m = 35. 45. 65. 79. 23.

7
Notice the square brackets in the beginning and at the end of the
sequence. True to its quick and dirty fame, Scilab wouldn’t mind if
you skip the commas.

-->m= [35 45 65 79 23]


m = 35. 45. 65. 79. 23
Can you recall what commotion C and Java compilers would have
made on such an occasion!

Suppose we want to calculate the average of these marks. no


variables, no algorithms, no loops! Just one command mean(m)

>m= [35, 45, 65,79,23]


m = 35. 45. 65. 79. 23.

-->mean(m)
ans = 49.4

Most of the popular statistical calculations can be done using similar


commands. If we want to add the marks, we perform

-->sum(m)
ans = 247.
We can also find out the deviation of the marks from the mean value
(standard deviation) using

-->stdev(m)
ans = 22.600885

If you are interested in finding out the maximum and minimum marks
max and min commands helps
->max(m)
ans = 79.

-->min(m)
ans = 23.

The simplicity of these codes might be of obvious interest to the


social science research community.

Till now, we have been discussing a sequence of numbers arranged in


a row called as vector. We have also discussed that a matrix is
tabular data , many times arranged in rows and columns. Let us see
the representation of a matrix,

8
-->b=[5,10,15; 20,25,30;35,40,45]
OR
>b=[ 5 10 15
20 25 30
35 40 45]
The above matrix has 3 rows and 3 columns and therefore is a 3*3
matrix.

If you want to interchange the rows and columns of the above matrix
(mathematically known as transpose) , we use the ’ operator as
follows:

b’
ans =
5. 20. 35.
10. 25. 40.
15. 30. 45.

You can see the rows have now become columns and columns have
become rows.There are some special matrices that are frequently
used in mathematical computations.
Scilab has commands to handle these matrices.

>zeros(3,1)
ans =

0.
0.
0.
You can see that a 3*1 matrix of all elements zeros are generated.

-->ones(2,2)
ans =

1. 1.
1. 1.

A 2*2 matrix of all elements ones is generated.. This is also known as


an identity matrix.

-->eye(2,2)
ans =

9
1. 0.
0. 1.

A 2*2 matrix with diagonal elements as ones is generated. Similarly


random numbers can be generated in a matrix as follows:

-->rand(2,2)
ans = 0.2113249 0.0002211
0.7560439 0.3303271
A 2*2 random matrix is generated by Scilab.

Pictorial representation of data is a very common requirement in all


fields where data arises from business to engineering and technology.
Scilab has a host of commands to satisfy these requirements.
Suppose the marks of 5 students are defined as a vector m=[33, 77,
45, 61,64] . We can plot this using the following command

plot(m)

Fig 2.6 Plot of m

Note that the given values are taken as y values and x values are
assumed as 1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0

Similarly, if the votes polled by different candidates in an election are


represented in a vector as n=[125000,35678,45678,56789,6000] ,We
can plot a pie chart of the same using:
pie(n)

10
Fig 2.7 A pie chart showing the votes polled by different
candidates

In the case of scientific calculations two dimensional and three


dimensional plots are very common. Consider the following table of x
and y values
x y
1 34
1.5 27
2 68
2.5 47

These can be defined as two vectors in Scilab


x=[1, 1.5, 2, 2.5]
y=[34, 27 ,68, 47]
The plot of y against x is obtained using the command
plot(x,y)

11
Fig 2.8 Plot of (x,y)
We have so far been discussing examples where Scilab manipulated
numbers. Let us now see how Scilab manages a different kind of data,
digital images. Of course, a digital image ia basically a matrix of
numbers. In fact every digital object, text, images, sound, video or
softwares ultimately boil down to numbers, to be specific zeros and
ones. To try out image processing, you need to have your favorite
image on the same folder from where Scilab has been launched, in our
example 1.jpg.
The image can be in any of the following formats .jpg, .bmp, .gif, .pnp
See how easy it is to bring the image on the screen.
x=imread(“1.jpg”)
imshow(x)

The command imshow reads an image into a Scilab variable x (which


is essentially a matrix )and imshow displays this image using the
matrix x. We will conclude this chapter rather abruptly, as the aim of
giving a quick taste of Scilab has been fairly done. We will now
proceed to a methodical study of Scilab.

12
Fig 2.9 Displaying an image using imshow()

13
Chapter 3
SCALARS & VECTORS
3.1Introduction
Scilab, just like Matlab focuses on matrices for handling huge dara.. A matrix is just a
rectangular array of rows (m) and columns (n). We refer to it in mathematics as an m*n
matrix. Any tabular data can be viewed as a matrix . For example, marks of 3 students in 3
examinations entered into an Excel spreadsheet in three rows is a matrix. Mathematically,
this matrix Mij can be denoted as
┌ ┐
│ 22 33 45 │
Mij = │ 56 55 64 │
│ 75 71 82 │
└ ┘

When a matrix has a single row of numbers we call it as a row vector. When amatrix
represents a single column of numbers it is called a column vector. If we consider the
marks of 1 student in 3 exam only, say mi, it is a row vector. If we c consider marks of 3
student sin one exam only, say mj, it is a column vector,

┌ ┐
mi = │ 22 33 45 │
└ ┘
┌ ┐
│ 22 │
mj = │ 56 │
│ 75 │
└ ┘

Thus, vectors are simply collection of numbers (and also any other type of data) arranged as
single row or single column. Scilab has avariety of of facilities to handle such data. This
chapter mainly deals with these features. There are then data without any array format,
known as scalars. Statements such as x=5, y=34.67 and z=’a’ references to scalars. Scalars
can also be complex numbers. Many mathematical functions are defined for scalar data.
Most of these are applicable on vectors (and many times, matrices too). We will discuss such
functions in the last section.

3.2Initialising vectors in Scilab


Vectors are denoted by square brackets in Scilab. A sequence of numbers separated by
comma (or simply spaces) defines a row vector. For example:

-->m= [35, 45, 65,79,23]


m = 35. 45. 65. 79. 23.

Spaces have the same effect as comma:

14
-->m= [35 45 65 79 23]
m = 35. 45. 65. 79. 23.

The same data can also be arranged a column vector. Here the
sequence of numbers are separated by semicolon

-->m= [ 35; 45; 65; 79; 23]


m =35.
45.
65.
79.
23.

Scilab has some short hand notations if the vector is am arithmetic progression of
numbers. To define [1, 2, 3, 4, 5, 6, 7, 8 ,9 10], we can command as follows:

A=[1:1:10]
A=1, 2, 3, 4, 5, 6, 7, 8 ,9 10

Here the starting number, increment value and upper limit are specified separated by
colon. Suppose we want to plot all the even numbers from 2 to 20 we proceed as follows:

B=[2:2:20]
B= 2. 4. 6. 8. 10. 12. 14. 16. 18. 20.

The increment (and the starting and ending values too) can also be a fractions. The
ending value need not be exactly calculated, the initialization would use the value
closest to the ending value. See example below

C=[0;0.3;1]
C=0.0, 0.3, 0.6, 0.9

If we are interested in creating a row vector or column vector of all


elements zeros, it can be done using a special zeros function. Let’s
see an example of a zero row vector of 5 elements

-->D= zeros (1,5)


D = 0. 0. 0. 0. 0.
Alternatively a zero column vector of 2 elements can be created as

-->zeros (2, 1)
ans = 0.
0.
We will later see that this function is defined generally on
matrices and vectors are matrices with number of columns or
rows as one.

15
3.3 Mathematical operations on vectors

The various mathematical operations possible on vectors are listed as


follows:
• Addition
• Subtraction
• Multiplication
• Division.
• Element wise multiplication
• Element wise division
• Transpose

Now consider two vector sequences a and b to demonstrate the


above operations:
a = [10,20,30]
b =[ 1, 2, 3]

3.3.1 Addition
Addition of two vectors a and b is performed using the + operator.
Both vectors must be of the same size. It is not possible to add a row
vector and a column vector.
-->a=[10,20,30]
-->b=[5,10,15]
-->a+b
ans = 15. 30. 45.

3.3.2 Subtraction
Subtraction uses the – operator. Here also both vectors have to be
of the same size.
-->a=[10,20,30]
-->b=[5,10,15]
-->a-b
ans = 5. 10. 15.

3.3.3 Multiplication
When multiplication is performed, one vector either a or b has to
be a row vector and the other a column vector. In this example a is a
row vector and b is a column vector.

-->a=[10,20,30]
-->b=[5;10;15]
-->a*b
ans = 700.

16
3.3.4 Division
Division is usually performed with a and b as row vectors.

-->a=[10,20,30];
-->b=[5, 10,15];
-->a/b
ans = 2.

3.3.5 Element wise multiplication


Element wise multiplication on two sequences can be done using the
.*operator. Both vectors must necessarily of the same size.

-->a=[10,20,30]
-->b=[5, 10,15]
-->a.*b
ans = 50. 200. 450.

3.3.6 Element wise division


Element wise division is done on two sequences using ./operator.
Both vectors must necessarily of the same size.
-->a=[10,20,30]
->b=[5, 10,15]
-->a./b
ans = 2. 2. 2.

3.3.7 Transpose
A row vector can be transformed into a column vector and vice versa
using ’operator.
Which is mathematically called as transpose?

>a=[10,20,30]
-->a'
ans =

10.
20.
30.

-->b=[5;10;15]

-->b'
ans = 5. 10. 15.

3.4 Relational operations on vectors

17
Scilab uses six relational operators for mathematic comparison of vectors. The operations
result in a vector of the same size, with the answer T when the relation is true and F
when it is false.

3.4.1 less than relational operator <


>x=[ 2 3 7 8], y=[2 4 5 1]
-->z=x<y
z =FTFF
In the above operation we can see that the second number 3 is less than 4. The
mathematic comparison 3<4 yields True. In all the other cases the result is False.

3.4.2 less than or equal relational operator <=

x=[ 2 3 7 8], y=[2 4 5 1];


-->z=x<=y
z =TTFF
Here the first number in vector x , 2 is equal to the first number 2 in vector y. The
comparison results in True as the result. Similarly the second number in vector x , 3 is
less than the second number 4 in vector y. Here also the comparison results in True as
the result. The third and the fourth numbers in vector x is less than their counter parts in
y. Hence results in answer False.

3.4.3 greater than relational operator >


>x=[ 2 3 7 8], y=[2 4 5 1]
-->z=x>y
z = FFTT
Here the third number 7 and the fourth number 8 in vector x are greater than their
counterparts in vector y and hence their mathematical comparison yields True value.

3.4.4 greater than or equal to relational operator >=


x=[ 2 3 7 8], y=[2 4 5 1]
-->z=x>=y
z = TFTT

Here all the numbers in vector x except the second number is greater than the
corresponding numbers in vector y. All the comparisons results in True value except for
the second where the result is False.

3.4.5 equal to relational operator ==


>x=[ 2 3 7 8], y=[2 4 5 1]
-->z= x==y
z = TFFF

Here the first number in vector x is equal to the first number in vector y .The comparison
results in True value.

18
3.4.6 not equal relational operator ~ =
x=[ 2 3 7 8], y=[2 4 5 1]
-->z=x~=y
z = FTTT

All the numbers in vector x are not equal to the corresponding numbers in vector y except
for the first number 2 in vector x which is same as the first number 2 in vector y. All
comparisons result in True value except for the first where the result is False.

3.5 Logical operations on vectors.

3.5.1 logical AND operator &


The operations result in a vector of the same size, with the answer T when both the
expressions are true and F when it is false.
..> x=[ 2 3 7 8], y=[2 4 5 1]
-->z=(x>y)&(x>2)
z = FFTT

Here we can see the condition x is greater than y and also that x is greater than 2 holds
good for the third and fourth elements of vector x

3.5.2 logical OR operator |


The operation result in answer T if either of the expressions are true
x=[ 0 3 7 8], y=[0 4 5 1]
-->z=x|y
z =FTTT
Here all the elements of vector x and vector y are non zero except for the first element
where x|y yields the answer F

3.5.3 logical Complement ~


This operation results in answer T if the expression is false and vice versa
x=[ 0 3 7 8], y=[0 4 5 1]
-->z=~(x|y)
z = TFFF

From the operation we can see that the result is the complement of x|y.

3.6 Built- in logical functions


• isempty()
• find()
• isreal()
• isglobal()

3.6.1 isempty()
This function returns a True value for an empty matrix
-->x=[0 3 7 8]

19
isempty(x)
ans = F

3.6.2 find()
This function finds the index of the non zero elements of a matrix
-->x=[0 3 7 8]
-->i=find(x>5)
i =3. 4.
3.6.3 isreal()
This function returns a True value for all the real elements of a matrix
-->x=[0 3 7 8]
-->isreal(x)
ans = T

3.6.4 isglobal()
This function returns a True value if the variable declared is global
-->x=[0 3 7 8]
-->isglobal(x)
ans = F

3.7 ELEMENTARY MATHEMATICAL FUNCTIONS

In this section , we will take a close look at a number of elementary


mathematical functions and related commands that are applicable to
vectors.

3.7.1 clean()
This function rounds all small values down to zero. Consider a matrix A
and the computation of A*A-1 in Scilab:

A=[ 1. 3. 2.
- 1. 2. 1.
4. 2. 1.] ;

-->B=A*inv(A)
B =
1. - 3.053D-16 - 8.327D-17
- 2.776D-17 1. - 2.776D-17
1.110D-16 - 3.331D-16 1.

Due to approximations2, some elements are shown as small nonzero


numbers. The function clean will round these numbers to zero,
cleaning the result to produce identity matrix., as expected

2
Though integers can be represented exactly by their binary equivalents in digital computers, real numbers
need not be. This limitation of the binary representation (indeed, of any number system) manifests itself
very visibly in some cases as seen here.

20
-->B=clean(B)
B =
1. 0. 0.
0. 1. 0.
0. 0. 1.

3.7.2 ceil()
This function rounds a floating point number to the next higher integer,
irrespective of the magnitude of the decimal point. ceil(1.x) is always 2
irrespective of the value of x.

>ceil([1.2 1.5 1.9 -1.2])


ans =
2. 2. 2. - 1.

3.7.3 floor()
This function rounds down a floating point number, to the next lowest
integer.

-->floor([1.2 1.5 1.9 -1.2])


ans =
1. 1. 1. - 2.

3.7.4 round()
This function rounds to the nearest integer, the usual way.

-->round([1.2 1.5 1.9 -1.2])


ans =
1. 2. 2. - 1.

3.7.5 fix()
This function rounds a floating point number towards zero
>fix([1.2 1.5 1.9 -1.2])
ans =
1. 1. 1. - 1.

The floor and fix functions rounds down to the nearest integer number.
Both gives the same result as with function int which returns the
integer part of a number.

-->int([1.2 1.5 1.9 -1.2])


ans =
1. 1. 1. - 1.

3.7.6 sign()

21
This function sign returns 1,-1 or 0 for a real number depending on
whether the number is positive, negative or zero

-->sign([1.2 1.5 1.9 -1.2])


ans =
1. 1. 1. - 1.

3.8 Mathematical functions on scalars


Most of the functions discussed in section 3.7 are applicable on scalars
(ciel, floor …hema to add). There are a small set of functions
applicable to scalars alone. We introduce them below.

3.8.1 modulo ()
This function is used to calculate the remainder of division of two
numbers.
-->modulo(5,2)
ans = 1.

3.8.2 Rat ()
This function is used to find the numerator and denominator of
therational approximation of a floating point number.
->[n,d]=rat(0.353535)
d = 28529.
n = 10086.
The result can be verified by calculating n/d

>n/d
ans = 0.353535

Yet another example is 0.33333333333333


-->[n,d]=rat(0.333333333333)
d = 3.
n = 1.

Here we have to provide a relatively large number of decimals to force


the result. A small number of decimal points will not produce the
required result. The function rat can be called using a second
argument which represents error or tolerance allowed in the
approximation.

-->[n,d]=rat(0.33333333,1e-4)
d = 3.
n = 1.

Here the tolerance of 1/10000 produces the approximation 1/3

22
3.8.3 sqrt()
This function returns the square root of a real or complex number. Let
us see an example of a real number
sqrt(2345.67)
ans = 48.432117

The remaining functions in this chapter are exponential functions.

3.8.4 exp()
The exponential function exp returns the value of ℮x for a real
number where e constitutes the basis of natural logarithm. This value
is given as a constant %e in Scilab

-->%e
%e = 2.7182818

Let us see an example of finding the exponent of a real number.


>exp(2.5)
ans = 12.182494

-->exp(-3.6)
ans = 0.0273237

3.8.5 log()
Natural logarithm is referred as log(). Let us see the natural logarithm
of a real number
-->log(2.35)
ans = 0.8544153

For a complex number represented as z=re , ln(z) =ln(r)+iθ

-->log(2+3*%i)
ans =1.2824747 + 0.9827937i

Besides the natural logarithm(logarithms of base e) , Scilab also


provides functions log10() and log2() that calculate logarithms of base
10 and base 2 respectively.

3.8.6 log10()
Here the base of logarithm is taken as10. If x=10y then y=log10(x).Here
is an example to illustrate this
-->log10(1000)
ans = 3.

3.8.7 log2()

23
Here 2 is the base of logarithm. If x=2y then y=log2(x). Let us see an
example

-->log2(8)
ans = 3.

3. 9 Complex numbers

A complex number z can be written as z=x+iy where x and y are real


numbers and i is √ -1 , an imaginary number. widely used in
Mathematics. Scilab supports complex numbers. We can say that x is
the real part of z and y is the imaginary part of z. A complex number
z=2.3+5.5 i can be written in Scilab as follows:

z=2.3+5.5*%i
z = 2.3 + 5.5i

We can separate out the real and imaginary parts with the real ( ) and
imag( ) functions.
x=real(z)
x= 2.3
y=imag(z).
y=5.5

real(0.6-0.8*%i)
ans = 0.6

-->imag(0.6-0.8*%i)
ans = - 0.8

The sign function when applied to a complex numbers, returns z/|z|.


The resulting complex number will have magnitude of unity.

-->sign(3-4*%i)
ans = 0.6 - 0.8i

The abs() function returns the magnitude of the complex number


-->abs(0.6-0.8*i)
ans = 1.

The functions clean, ceil, floor , int, round and fix can be applied to
complex numbers also

z=2.3+5.5*%i
z = 2.3 + 5.5i
-->ceil(z)

24
ans = 3. + 6.i
-->floor(z)
ans = 2. + 5.i

-->int(z)
ans = 2. + 5.i

-->round(z)
ans = 2. + 6.i

-->fix(z)
ans = 2. + 5.i

The square root of a negative real number(x<0) is calculated as √-


x=i√x
-->sqrt(-2345.67)
ans = 48.432117i

Logarithms also can be calculated for complex numbers. For a complex


number represented as z=reiθ , ln(z) =ln(r)+iθ

-->log(2+3*%i)
ans =1.2824747 + 0.9827937i

3.10 Trigonometric functions


The basic trigonometric functions sine(sin), cosine(cos), and
tangent(tan) are supported in Scilab.. The trigonometric functions are
defined in terms of the angles and sides of a right triangle.

Hypotenuse
Opposite side

Adjascent side

Sin(α)=opposite side/Hypotenuse; cos(α)=adjascent side/ Hypotenuse


and tan(α)=opposite side/Adjascent side. Scilab assumes the angles to
be in degrees. We shall for example calculate these functions for a
value of α=45

->sin(45)
ans = 0.8509035

-->cos(45)

25
ans =.5253220

-->tan(45)
ans = 1.6197752

sec, cosec and cot ----???

3.11 Inverse trigonometric functions

If sin(y) =x then y=sin-1 (x) =asin(x), If cos(y) =x then y=cos-1 (x)


=acos(x), If tan(y) =x, then y=tan-1 (x) =atan(x). We will find these
values for x=0.5

>asin(0.5)
ans =0.5235988

-->acos(0.5)
ans =1.0471976

-->atan(0.5)
ans =0.4636476

Chapter 4
MATRICES
4.1 Introduction
We have already mentioned that matrices are central to both Matlab and
Scilab. In this chapter we will attempt to cover a wide variety of Scilab
features on matrix handling. A matrix, in layman’s language is tabular data
arranged in rows and columns. Let us see an example of a matrix
┌ ┐
│ 11 12 13 │
A= │ 21 22 23 │
│ 31 32 33 │
└ ┘

This can be defined in Scilab in a single line, with rows separated by semi-
colons or in three lines, with a line break after each row, as shown below.

-->A= [ 11 12 13 ; 21 22 23 ; 31 32 33]
A= [ 11 12 13
21 22 23
31 32 33]

26
In chapter 3 we have seen that a vector is a special case of a matrix arranged
in a single row or single column. For instance, B= [ 23, 34, 56, 78, 90]
represents a vector. Matrix having a single element is treated as a scalar.
A=39 and A=[39] are treated the same way by Scilab.

Any element of the matrix can be referred to by specifying its row and column
indices. Note that the indices start from 1 and not 0, as in many modern
programming languages. If we want to access the second element of the first
row, we may referred to it as ‘A(1,2)’.

Column  1 2 3 Row ↓
┌ ┐
│ 11 12 13 │ 1 A(1,2)
A= │ 21 22 23 │ 2
│ 31 32 33 │ 3
└ ┘
The first number in parenthesis refers to the row to which the element belongs
and the second number indicates the column containing the element.

-->A(1,2)
ans =12.

Similarly we can display the third element of the second row using
-->A(2,3)
ans =23

To overwrite any defined value, we can simply reassign


----A(2,3)=0
A =
11. 12. 13.
21. 22. 0.
31. 32. 33.

We will now look at the following categories of matrix commands


• Matrix Arithmetic and Relational operators
• Basic matrix processing
• Mathematical functions of matrices

4.2 Arithmetic operators for Matrices


In matrix arithmetic we have basically three kinds of commands to be aware
of
• Basic arithmetic
• Element wise arithmetic and Left and right division
• Relational and Logical operators

27
4.2.1 Basic arithmetic
Addition, subtraction and multiplication are done on matrices in Scilab in
exactly the same way as they are traditionally defined in mathematics. These
operations work only if the size of the matrices are compatible. In case of
addition and subtraction, the matrices have to be of exactly same
dimensions. In case of multiplication, an (m × k) matrix is compatible with
only an (k×n) matrix, ie, the second matrix must have same number rows as
the number of columns of the first matrix. The following examples illustrate
addition subtraction and multiplication.

--> a= [1 2; 3 4]
-->b=[2 3; 4 5]
-->c=a+b
c =
3. 5.
7. 9.
-->d=b-a
d =
1. 1.
1. 1.
-->e=a*b
e =
10. 13.
22. 29.
Division of matrices is not straightforward and involves a concept of matrix
inverses, which we will discuss in another section. However, here it may be
noted that division operator has the same effect as multiplication by inverse.
By using the operator / and \, we can choose which matrix to invert. a\b is
equivalent to inv(a)*b and a/b is equivalent to a*inv(b). We show below the
equivalence using the inv( ) function which we will look at closely in later
sections.

-->a=[1 2; 3 4]
-->b=[2 3; 4 5]
-->a\b
ans =
0. - 1.
1. 2.
-->inv(a)*b
ans =
0. - 1.
1. 2.
-->a/b
ans =
1.5 - 0.5

28
0.5 0.5
-->a*inv(b)
ans=
1.5 - 0.5
0.5 0.5

4.2.2 Element wise arithmetic


Even though element wise operations on matrices may not always be
mathematically meaningful, in practice many uses of such operations may
occur. Scilab differentiates elementwise matrix operations with a dot
preceding the operator. It may be noted that the traditional addition and
subtraction are element wise operations.

See the examples below which demonstrate element wise multiplication and
divison. Be sure to compare the results with those of traditional multiplication
and division in section 4.2.1. Also note that the matrices only need to be of
the same size to be compatible, unlike in the case of traditional multiplication
where they need to have dimensions (m×k) and (k×n).

-->a=[1 2; 3 4]
-->b=[2 3; 4 5]
---> a.*b
ans =
2. 6.
12. 20.
Element wise division has left and right options, indicated by / and \
operators. See examples below. Both matrices a and b must be of the same
size. In left division, the elements of b are divided by the elements of a. In
right division, the elements of a are divided by the elements of b
-->a=[1 2; 3 4]
-->b=[2 3; 4 5]
-->a.\b
ans = 2. 1.5
1.3333333 1.25
-->a./b
ans = 0.5 0.6666667
0.75 0.8

4.3 Basic matrix processing

In this section we will focus on matrices with various data types and
then the basic matrix operations- transpose, trace, determinant, eigen
value etc

4.3.1 Matrices with various data types

29
Matrices can hold a variety of data types. The elements all need to be
of the same type except in the case of Lists. The following are the
major types of data that can be held by matrices such as constants,
characters, strings, boolean, polynomials. Lists can hold a variety of
data and also matrices themselves.

Constant matrices are already familiar to you. They can hold numbers
as in the following example

┌ ┐
│ 11 12 13 │
A= │ 21 22 23 │
│ 31 32 33 │
└ ┘
The numbers can have decimal parts also. In addition, variables
(with values pre-defined) can also appear as elements of matrices.
For example,

-->x=22

-->A= [ 11 12 13
--> 21 x x+1
--> 31 32 33]
A =
11. 12. 13.
21. 22. 23.
31. 32. 33.

Character data defined in single quotes such as ‘a’ , ‘+’, ‘o’ etc can
be elements of matrices.
-->B= [ 'm' 'a' 't'
--> 'h' 'a' 't'
--> 'r' 'a' 't' ]
B =
!m a t !
! !
! h a t !
! !
! r a t !

It may be noted that character matrices are displayed with special


brackets built with ‘ ! ’ mark. Character strings can also be elements
in matrices as follows.
-->C=[ 'cat' 'rat'
--> 'mat' 'hat' ]

30
C =
! cat rat !
! !
!mat hat !

A very special kind of matrix that Scilab supports is a polynomial


matrix. The use of this other than in mathematics, shall be dealt with
in Chapter 12 on Control Toolbox. For defining a polynomial matrix D
given by
┌ ┐
│ │
D = │ 1+x 2 -3+x2 │
│ 1 +x x-5 │
└ ┘
we must make x a polynomial variable. This is done as follows:

-->x=poly(0, 'x');
-->D=[ x^2+1 x^2-3
--> x+1 x-5]
D =
2 2
1+x -3+x

1+x -5+x

We can do mathematical operations like addition, subtraction,


multiplication and inverse operations on polynomial matrices.
--->x=poly(0, 'x');
-->D1=[ x^2+1 x^2-3
--> x+1 x-5 ]
D1 =
2 2
1+x -3+x

1+x -5+x

-->D2= [ x^3+2 x^3-6


--> x^2+2 x^2-5 ]
D2 =

3 3
2+x -6+x

2
2
2+x -5+x

31
-->D1+D2
ans =

2 3 2 3
3+x+x -9+x+x

2 2
3 + x + x - 10 + x + x

-->D1-D2
ans =

2 3 2 3
-1+x-x 3+x-x

2 2
-1+x-x x-x

-->D1*D2
ans =

2 3 4 5 2 3 4 5
-4+x+x+x+x 9 - 14x + x + x + x

2 3 4 2 3 4
- 8 + 4x - 5x + 2x + x 19 - 11x - 5x + 2x + x

-->inv(D1)
ans =

2
-5+x 3-x
----------- -----------
2 2
- 2 + 4x - 6x - 2 + 4x - 6x

2
-1-x 1+x
----------- -----------
2 2
- 2 + 4x - 6x - 2 + 4x - 6x
Boolean values of True and False are defined as constants %t and %f
In Scilab. They can be used as elements in matrices.

-->E=[ %t %f

32
--> %t %f ]
E =
TF
TF

Such matrices are usually generated when we do element wise


relational operations on matrices.
-->[1 2]==[1 3]
ans = T F
So far we have seen matrices of different data types, but in all cases
every matrix had a single data type. List is a special facility used to
group a set of heterogeneous objects into a single object. It is similar
to struct in C programming language. Let us consider creating a list
containing two data types, say a string and a number. Let us assume
they are the name and marks of a student. Let us denote the list as
student. We can create such a list with data
‘Gayathri’ for name and 95 as marks by using the following
command.

F=tlist(‘student’, ‘name’, ‘marks’), “Gayathri”, 95)



List name

List creation command

Variable
name

-->F=tlist(['student', 'name', 'marks'], "Gayathri', 95)


F =

F(1)
!student name marks !

F(2)
Gayathri

F(3)
95.

We can extract an entry from the list by specifying the item, as


follows:

>F('name')
ans =
Gayathri

33
-->F('marks')
ans =
95.

4.3.2 Basic Matrix Operations

In this section we shall see how to handle a matrix, including


navigationg through it in special ways and implementing common
operations such as transpose , inverse etc.

One of the basic information about a matrix is its dimensions. For two
dimensional matrices, it is of the form [m×n], where m is the number
of rows and n is the number of columns. We can use size() function in
scilab to determine the dimensions of a matrix, as demonstrated below

A= [ 11 12 13
--> 21 22 23
--> 31 32 33]

-->size(A)
ans =
3. 3.

The answer shows that there are three rows and three columns for the
matrix A, or A is a [3*3] matrix.

Square matrices (matrices with equal number of rows and columns)


have their diagonal elements defined as indicated below

┌ ┐
│ \ 11 \ │
A= │ \ 22 \ │
│ \ 33 \ │
└ \ ┘

If a ij is the matrix element then in general all elements with i=j define
the diagonal elements. In Scilab we use the function diag() to find the
diagonal elements.
-->diag(A)
ans =
11.
22.
33.
We can find out the trace of a matrix, once the diagonal elements are
found out. Trace is the sum of all the diagonal elements

34
 trace(A)
ans=
66
The lower triangular matrix of A which is all elements in the diagonal
and below it, can be found with tril( ) function.
-->tril(A)
ans =
11. 0. 0.
21. 22. 0.
31. 32. 33.

Similarly, the upper triangular matrix which is a square matrix whose


elements below the diagonal elements are zeros is obtained using the
triu( ) function.
-->triu(a)
ans =
11. 12. 13.
0. 22. 23.
0. 32. 33.

Another basic operation is transpose of a matrix which is obtained by


inter changing rows and columns. of a given matrix. The figure below
illustrates a matrix A and its transpose AT

┌ ┐
│ 11 12 13 │
A= │ 21 22 23 │
│ 31 32 33 │
└ ┘

┌ ┐
↓ │ 11 21 31 │
AT= 12 22 32 │
│ 13 23 33 │
└ ┘
In Scilab we use ’ operator to find the transpose

--->A'
ans =
11. 21. 31.
12. 22 32.
13. 23. 33.

Scilab uses the : operator to specify range of rows and columns


Suppose we want to select rows rows 2 and 3 alone and all columns ie;
1-3, we proceed as follows:

35
-->A(2:3, 1:3)
ans =
21. 22. 23.
31. 32. 33.

If you want to navigate through the entire rows, but only columns 1
and 2 type colon followed by the columns( ie; 1:2) to be displayed
-->A(: , 1:2)
ans =
11. 12.
21. 22. .
31. 32.
See an example of specifying entire columns and rows 1 and 2
--->A (1:3, :)
ans =

11. 12. 13.


21. 22. 23.
The entire matrix can be reshaped into a vector column wise
>b=a(:)
b =
11.
12.
13.
21.
22.
23.
31.
32.
33.
The ‘:’ facility makes it possible to extract a sub matrix of A, by
specifying the required rows and columns of it.
┌ ┐
│ 11 12 13 │
A= │ 21 22 23 │ C
│ 31 32 33 │
└ ┘

-->C=A(2:3, 2:3)
C =

22. 23.
32. 33
We can delete a row or column of a matrix by setting it to a null vector
[ ]. A null vector is a vector having no elements in it . Here is an
example of deleting the second row.

36
-->A(:, 2)=[ ]
A=
11 12 13.
31. 32 33.

You can append a row or column to an existing matrix if the row or


column has the same length as the existing matrix. See this example
of appending a row to the matrix A

-->P=[41 42 43]
-->A=[A ; P]
B =
11 12 13
21 22 23
31 32 33
41 42 43.

Like wise, we can see how a column can be appended

-->Q= [14
24
34]
-->B=[A Q]
B =

11 12 13 14
21 22 23 24
31 32 33 34
We can add elements to a null vector, which is a vector having no
elements in it ..
-->e=[ ]
--->e=[e; 1 2 3]
e =
1. 2. 3.
A comparatively involved concept related to matrices is their eigen
value and eigen vectors. For every square matrix A, the equation A-λI
=0 is known as the characteristic equation.
λ is a vector whose values are known as eigen values and columns
of the matrix with λ ‘s as diagonals are known as eigen vectors. An
insightful explanation of eigen values and vectors is beyond the scope
of this book. We will only briefly note that every matrix can be
considered as a transformation operator as in the example below. A
point with coordinate x,y can be transformed into x’, y’ by the
transformation

37
[x’,y’]=A[x
y]

If A=I, then [x’y’]=[x,y]. If A=[-1,0; 0,1] then [x’y’]=[-x,y], resulting in


a reflection of the point with respect to y axis. A general matrix A=[a,
b; c, d] will result in x’=ax+by and y’=cx+dy. It is well known that
such transformations have certain axes which are special, as points on
these axes are transformed as points along the axes only. These axes
represent the eigen vectors of the transformation and their scaling
factors represent eigen values. The eigen vectors and eigen values
have wide applications in applied mathematics, computer graphics,
soft computing and control systems. We will limit our discussion to a
simple example showing evaluation of eigen values and vectors.
Consider A=[1 2 ; 3 4] Its eigen values can be calculated as below
based on the equation A-λI =0

[1 2; 3 4] –[ λ1 0; 0 λ2]= **************

The above computation can be achieved with spec( ) function in Scilab.

-->A=[ 1 2; 3 4];
-->spec(A)
ans =
5.3722813
- 0.3722813

The eigen vectors corresponding to the eigen values can be computed


by the same command by specifying variables for storing both.

-->[x,y]=spec(A)
y =
5.3722813 0
0 - 0.3722813
x =
0.4159736 - 0.8245648
0.9093767 0.5657675

We find that eigen values appear as diagonal elements in the


variable y. The eigen vectors appear as columns in the matrix x.

38

You might also like