Sie sind auf Seite 1von 94

SCILAB

documents
Fall 2001

By
Gilberto E. Urroz, Ph.D., P.E.
Associate Professor
Class notes for the classes:

ENGR 2200: Numerical Methods in Engineering I


CEE 6510: Numerical and Statistical Methods in Civil Engineering

August-December 2001

Getting started with SCILAB 2.6


You need to have downloaded SCILAB 2.6 from the INRIA website as well as the PFE text editor
from the corresponding website. There are links to these two software packages in the web
page:
http://www.engineering.usu.edu/cee/faculty/gurro/Scilab.html
Typically, the SCILAB program will be installed in the location:
c:\Program Files\Scilab-2.6
while the PFE program can be unzipped into any folder in your computer. For example, my
copy of PFE is stored in the location:
c:\Program Files\PFE_Folder
It is a good idea to create shortcuts to both programs in your desktop so that you can launch
them with a simple click. [You can always launch SCILAB by using Start > Programs > Scilab2.6
> Scilab 2.6].
SCILAB functions from the textbook
In the web page http://www.engineering.usu.edu/cee/faculty/gurro/Scilab.html you can find
a link to download a zip file containing the files corresponding to all the functions presented in
the textbook Numerical and Statistical Methods with SCILAB for Science and Engineering.
My recommendation for the location of these functions is as follows:
1. In your own computer, create a folder called work at c:\Program Files\Scilab-2.6\work
and store all the functions under that folder.
2. If using the PC Lab computers, create a folder called work in a zip disk. Thus, if the
zip disk in a particular computer is referred to as d:\, your directory will be d:\work
In order to load the functions to your SCILAB workspace when using your own computer, it is
recommended that you create a text file (using PFE) that contains the command:
chdir('c:\Program Files\Scilab-2.6\work')
Call this file c:\scilabwork (no .txt suffix). Similarly, if using a zip disk in a PC lab computer,
you want to create a file called d:\scilabwork containing the command:
chdir('d:\Program Files\Scilab-2.6\work')
Whenever you start a SCILAB session, if you are going to be using any of the SCILAB functions
contained in the folder work, use the command:
--> exec(c:\scilabwork)

if using your own computer, or


--> exec(d:\scilabwork)

if using a PC lab computer.

Executing this command will change the current SCILAB directory to your work folder and allow
you access to any of the functions contained in that folder. Thus, if you wanted to load the
function Euler1 (numerical solution to an ordinary differential equation using Euler 1st -order),
you simply type in your SCILAB workspace:
--> getf(Euler1)

Note: while most functions in the folder work are named without a suffix, a few of them use
the .txt suffix. Thus, if a function fails to load when using the SCILAB command getf with the
function name as its argument, try using getf with the name of the function with the suffix .txt
Where to store the files you create
You can store the files that you create from SCILAB applications into your work folder, or, if
you prefer to keep them separated from the textbook functions, store them in a different
folder, say, one called myScilab. Thus, if you have installed SCILAB in your own computer, you
could create your myScilab folder in device c:\ (i.e., c:\myScilab), or, if using a PC lab
computer, in device d:\ (i.e., d:\myScilab).
There are two common ways of creating a file while working with SCILAB. One way consists in
creating a file that collects all output from a SCILAB session by using the command diary. For
example,
--> diary(c:\myScilab\file1)

will create a text file called file1 under folder myScilab in disk c:\ if you are using your own
computer. If using a PC lab computer, you may want to use instead the command:
--> diary(d:\myScilab\file1)

A second common way of creating files for a SCILAB session is when you type your own function
or command script using a text editor (i.e., Notepad or, preferably, PFE). When using PFE, for
example, you need to create a new file by using File > New. After typing the script or function
in the file, you want to save it in your myScilab folder by first using the option Change
directory under the File menu, and then using the option Save As.. in the File menu.
When you change the current directory under PFE (by using File > Change directory), PFE
records that particular directory in its memory. The next time you need to change directory in
PFE, the directory you used (i.e., myScilab) will be available in the list box that shows up when
selecting the option File > Change directory. Simply select the directory of interest (i.e.,
c:\myScilab or d:\myScilab) before saving your file.
Files can also be created from within SCILAB (or from within a SCILAB script or function) by
using the function file with the option open, e.g.,
--> u = file(open,c:\myScilab\data3.txt,new)

This command creates a new file whose path is c:\myScilab\data3.txt. More details about input
and output to files is presented in Chapter 2 in the textbook.
What to study on your own?
The textbook (Numerical and statistical methods with SCILAB for science and engineering) was
developed so that the reader can start working with SCILAB right away. The reader is

encouraged to read the introductory material in each chapter and to try the exercises shown in
the textbook. Some of the materials that the reader can study on his or her own are those
subjects presented in Chapters 1 through 5. Chapter 1 is a quick introduction to the software
including the available menus in the SCILAB interface and some aspects of its basic operation.
Note: Since the original textbook was developed for SCILAB version 2.5, while the current
version is SCILAB 2.6, I have updated Chapter 1 for the latest version of the software. The
chapter is available for download in the web site:
http://www.engineering.usu.edu/cee/faculty/gurro/Scilab.html

Chapter 2 is a quick introduction to programming with SCILAB by presenting the basic


components of conditional constructs and loops, input-output, and some string functions.
Chapter 3 includes a number of applications of two- and three-dimensional graphics. Chapter 4
deals with operations with vectors, while Chapter 5 deals with matrices and linear algebra
subjects.
The subjects covered in these five chapters are useful in the solutions of numerical and
statistical methods presented in the remaining chapters of the textbook (Volumes I and II),
thus, I recommend you study these first five chapters on your own very carefully. Some of the
subjects will be covered in the lectures, however, there is no better recipe to learning the
application of SCILAB (or any software, for that matter) than trying the exercises yourself.

Using SCILAB at the PC LAB

Page 1 of 2

Using SCILAB at the PC LAB (EL 105)


To launch SCILAB or PFE
Click on Start>Programs>MathTools>Scilab>Scilab to launch SCILAB
Click on Start>Programs>MathTools>Scilab>Pfe32 to launch the program editor (PFE)
Click on Start>Programs>MathTools>Scilab>Read Me to see additional information on SCILAB

Loading functions from the textbook


Homepage
Classes
ENGR 2200
CEE 3030
CEE 6510
CEE 6580

My Books
SCILAB
Maple
HP 48 G
HP 49 G
Visual Basic
StarOffice
R

The functions from the textbooks Numerical and Statistical Methods with SCILAB for Science and Engineering vols. 1 & 2
are available at
o:\scilab-2.6\BookFunctions\Scilab_Book_Functions
To facilitate the loading of these functions, create a text file (e.g., using PFE) that contains the line:

chdir(o:\scilab-2.6\BookFunctions\Scilab_Book_Functions)
and save this file in your zip disk (d:\) or floppy disk (a:\) under a name you can easy remember, e.g., scilabfunctions (no
suffix). Then, if you need to load the textbook functions, simply execute the script in file scilabfunctions from within
SCILAB, i.e., type the command:

-->exec(d:\scilabfunctions)
or

-->exec(d:\scilabfunctions)
This will place the sub-directory

o:\scilab-2.6\BookFunctions\Scilab_Book_Functions

as your current SCILAB directory.

To load any function simply use function getf, e.g.,


-->getf(CrossProd)

http://www.engineering.usu.edu/cee/faculty/gurro/SCILABPCLAB.htm

12/7/2001

1 Introduction to SCILAB
This chapter is intended to get the user started using SCILAB through simple exercises in
numerical calculations. The chapter starts by describing how to download and install SCILAB in
a Windows environment. Installation of the software in other operating systems is very similar
and is explained in detail in the SCILAB website.
What is SCILAB?
SCILAB is a numerical, programming and graphics environment available for free from the
French Government's "Institut Nationale de Recherche en Informatique et en Automatique INRIA (National Institute for Informatics and Automation Research)." It is similar in operation
to MATLAB and other existing numerical/graphic environments, and it can be run using a
variety of operating systems including UNIX, Windows, Linux, etc.
SCILAB is a self-contained package including a large number of intrinsic numeric, programming
and graphics functions. Once unpacked and installed in your computer it will consume about
50 MB of your hard disk. Make sure you have at least that much memory in your hard disk
before downloading and installing SCILAB.
Where to find SCILAB
SCILAB is available for free from the SCILAB web page: http://www-rocq.inria.fr/SCILAB/
Once, you have accessed this web page, follow the procedure described below to download and
install SCILAB in your computer.
How to download the software
Click on the link labeled Download Scilab 2.6 . This will take you to an information page.
Next, click on the link labeled ftp.inria.fr in directory. This will send you to the ftp download
page ftp://ftp.inria.fr/INRIA/Projects/Meta2/Scilab/distributions/. From that directory you
need to click on the link Scilab26.exe,or on the link Scilab26.zip if you prefer a zip file
containing the installation program. Save the program it in the directory of your choice.
How to install SCILAB
Unpack SCILAB26.zip, if you downloaded that version of the installation program. Run the
program SCILAB26.exe and follow the instructions in your screen. In a Windows system, SCILAB
2.6 is typically installed in the sub-directory c:\Program Files\Scilab-2.6
How to get documentation for SCILAB
To get documentation on SCILAB scroll down the SCILAB main web page and click on the
documentation link. This will take you to their documentation page, showing the following
options:

Introduction to Scilab
Communication Toolbox Documentation
Signal Processing
Lmitool: Linear Matrix Inequalities Optimization Toolbox Documentation
Metanet User's Guide and Tutorial
Scicos
Scilab's Internals Documentation

2001 - Gilberto E. Urroz


All rights reserved

HOWTO's Scilab
Scilab's demonstrations

The documentation is available in html format, which you can access by clicking in any of the
options shown above. If you want to have your own copy of the documentation in PostScript or
PDF format, press the appropriate option in the web page.
Things that SCILAB lets you do
SCILAB can be used for simple arithmetic operations as well as for some algebraic operations,
to generate graphics, to program functions, and to solve linear algebra problems and ordinary
differential equations, among other things. You can also program SCILAB and produce simple
or fancy graphic user interface components for your program.

Getting started with SCILAB


To get started, launch the SCILAB application.
To load a value into a variable use an assignment statement (one that includes the
equal sign), e.g., a = 3.2. Try the following exercises for simple arithmetic operations:
a = 3.2 <return>
b = 6.4 <return>
a+b <return>
a-b <return>
a*b <return>
a/b <return>
a^b <return>
who <return>
The last command will return a list of the active variables in your worksheet. Many of
them are system variables that cannot be modified by the user.
SCILAB has a number of special constants, such as %i, %pi, and %e, corresponding to the
unit imaginary number, = ratio of circumference to diameter, and e = the base of the
natural logarithms, respectively. The value %eps is another special constant corresponding
to the maximum value for which 1 + %eps = 1. Other important constants are %inf =
infinity, and %nan = not-a-number. Boolean (i.e., logical ) constants are %t = true and %f =
false.
Try the following exercises to see what values are returned by SCILAB:
%e <return>
%i <return>
%pi <return>
%eps <return>
%inf <return>
%nan <return>
%t <return>
%f <return>

2001 - Gilberto E. Urroz


All rights reserved

Comments in SCILAB are represented by the double forward slash (//). Anything in
front of // is taken as a comment. For example, enter:
a = 4.5 // redefining a <return>
SCILAB will return the value of 4.5 for a and ignore the comment after the //
Scalars: real, logical, string, polynomial, rational, and basically any object that is not
between brackets in SCILAB is referred to as a scalar. Examples are:
a = 1 // real constant <return>
2>1 // Boolean constant (i.e., logical) <return>
'my name' // character string or constant <return>
r = poly(1.,'x') // polynomial with variable 'x' and root at 1.0 <return>
q = y/r // rational expression <return>
Using the "Introduction to SCILAB" demo: SCILAB is provided with a number of demos to
show the software abilities. To access the demos click on the Demos menu. This will
provide a dialogue window (SCILAB Choose) with a list of subjects, such as Introduction to
SCILAB, Graphics, etc. Select the Introduction to SCILAB, and press OK. A file with SCILAB
commands is loaded in memory. To see each line press <return>. The lines are shown and
executed (if executable). Comments have been added to each line to explain the
operation shown. (The entire demo session is listed in pages 118 to 137 of the
documentation file Introduction to SCILAB.) Keep pressing the <return> key to observe a
good summary of SCILAB abilities. In particular, pay special attention to item 2 (MATRICES)
since SCILAB is a matrix-based system. Also of interest are the items labeled OPERATIONS
and SOME NUMERICAL PRIMITIVES. (The term primitives is used to refer to simple
numerical operations pre-programmed in SCILAB or any other numerical environment).
Using other demos: To see any of the other demos provided with SCILAB select the
option Demos from the File menu, then select the Demo subject you want (e.g. , Graphics:
Introduction), and select a particular demo (e.g., plot2d3 in Graphics: Introduction).
Notice that, when using graphics in SCILAB, the program generates a window called
SCILABGraphic0.
Getting help: In the Help menu there are three options that you can use to get help
from SCILAB:
Help Dialogue: provides a list of help items classified by chapters. There will be two
windows available using this option, the lower window shows the chapter titles while
the upper window shows the subjects in the chapter currently selected. Select the
item you want to display and press the Show button located to the left side of the help
window.
Topic: enter a topic you want help with in the window shown when using this option
and press the OK button. If no help is available you will get a message indicating so in
the main SCILAB window. If help is available, SCILAB will show you the corresponding
instructions. For example, use this option and request information on the keyword inv.
It will give you information on the inverse operation for matrices.
Apropos: enter a keyword related to the topic that you are looking for (e.g., inverse)
and press the OK button. You will see a window with topics including the keyword you
selected. Scroll through the list and find that topic closer to your interest (e.g., inv matrix inverse), and press OK to get information on that particular topic.

2001 - Gilberto E. Urroz


All rights reserved

Other menus in the SCILAB worksheet

The "File" menu: The following options are available in the File menu:
Getf: use it to load a function. (Type help getf for additional information).
Exec: to execute a script file. (Type help exec for additional information).
Save: to save variables (Type help save for additional information).
Load: to load a saved variable (Type help load for additional information).
Change Directory: self-explanatory.
Get Current Directory: self-explanatory.
The "Functions" menu:
Copy to Clipboard: lets you copy highligted text to the Windows clipboard
Paste: lets you paste text in the clipboard to current SCILAB prompt location
Choose Font : lets you choose the font in the main SCILAB window
History: access to a menu of commands for editing SCILAB command lines.
character ^ in this menu stands for the Ctrl key.

The

The "Control" menu


Restart: clears all user-defined variables and initializes environmental variables.
Pause: switch control to pause mode. Used mainly for debugging SCILAB functions.
Resume: resume execution after a pause.
Abort: end execution of current program.
Interupt : interrupt execution of current program.

Pause mode: when entering Pause mode, SCILAB creates a new (numbered) prompt. In this
mode you can enter SCILAB commands without affecting the main line of calculation
(represented by the main SCILAB prompt !). To get into the pause mode you can type
pause at the main prompt or click on the Pause option in the upper menu bar of the main
SCILAB window. (The option Interupt [sic] in the upper menu bar also allows you to enter
into pause mode, however, it will interrupt any operation currently being executed by
SCILAB).. You can have several levels of pause, one for every time you enter a pause
command. To leave the current pause level and move the upper one type return. To
move up two levels use the command quit. (Note, when used in the main SCILAB prompt,
quit will terminate your SCILAB session). For more information on the pause mode use the
help feature as described above, or simple type help pause.

Simple operations with SCILAB


Simple scalar operations: the following exercises will get you acquainted with a few of
SCILAB's abilities for operating with scalar values.
a = 2 <return>
b = 3 <return>
Save a <return>
clear a <return>
a <return>
b <return>
load a <return>

2001 - Gilberto E. Urroz


All rights reserved

a <return>
exp(a) + exp(b) <return>
sin(a*%pi/b) <return>

(Note: the clear command is used to eliminate variables, as in clear a, as shown above. By
itself, clear deletes all variables recently defined. Therefore, be very careful when using this
command).

Vectors:
To enter vectors use the square brackets and separate the elements with commas or
blanks for a row vector, e.g.: v = [-1. , 2., %pi].
The transpose of a vector (or matrix) is expressed using the apostrophe, for example,
type: v'
To enter a column vector, use any of the following procedures: w = [3; -2; 5] <return>
or
r = [6 <return>
-2 <return>
10 ] <return>
You can create a row vector by indicating a starting value, an increment (or
decrement), and an ending value, all separated by the colon (:) operator as follows:
vector_name = starting_value : increment : ending value

for example: x = -10.0 : 0.5 : 10.0 <return>


If you prefer to store it as a column vector, try the following: xt = x' <return>
Let's apply a function to the vector x, try: y = sin(x*%pi/10) <return>
We can plot the vectors x,y using: plot(x,y,'x','y','first plot') <return>
[Type help plot <return> for more information]
Let's restart SCILAB and operate with other vectors: Press the Restart option in the
upper bar menu.
Enter the row vectors, u = [-1. 2. 3.] and v = [6. -10. 0.]
Perform the following operations:
u + v <return>
u - v <return>
u*v <return>
u*v' <return>
u'*v <return>
To extract elements of the vectors, try:
u(3) <return>
u(2) + v(1) <return>
Try the following exercise: a = 1; b = 2; c = 3; r = [a, b, c] <return>
To suppress SCILAB responses use the semi-colon after entering a command. For
example, try: s = [-1., 2.]; <return>
Vectors can also contain characters as their elements, e.g., letters = ['a', 'b',
'c', 'd'] <return>
Note: Expressions such as a, b, etc., are referred to as strings. Therefore, only
those string operations such as concatenation, part, etc. are allowed for vectors with
character elements. SCILAB strings and string operations are presented in a subsequent
chapter.

2001 - Gilberto E. Urroz


All rights reserved

Matrices:
Here are several ways to enter matrices: (press Restart)
A = [1. 2. 3.; 4. 5. 6.; 1. -1. 0.] <return>
B = [ 1. 1. 1. <return>
2. 3. -1. <return>
5. 7. -2. ] <return>
u = [1. 3. -5. ]; v = [4. 2. 3. ]; w = [-1. 0. 1.]; <return>
C = [u; v; w] <return>
r = [u, v, w] <return>
D = [u' v' w'] <return>
Matrix operations: try the following operations:
A + B <return>
C - D <return>
A*B <return>
B*A <return>
C*u <return>
D*v' <return>
rank (A) <return>
inv(A) <return>
cond(B) <return>
det(C) <return>
A*inv(A) <return>
inv(B)*B <return>
spec(A) <return> (calculates eigenvalues)
trace(C ) <return>
(Note: to find out more about any of the commands listed here type help followed by
the command name, e.g., help spec).
Solution of linear systems: two possibilities are:
(Press Restart)
A = [1. 3. 2.; 2. 1. -1.; 5. 2. 1.]; b = [2; 3; 4]; <return>
xa = inv(A)*b <return>
xb = linsolve(A,b)<return>

(Note: type help linsolve to learn more about this command).

Simple SCILAB Input and Output


Output: To get a list of your current session use the function diary. The format is as
follows: diary (output_filename), where the filename is written within quotes. To end
collecting output in the current diary output file use diary(0). For example, try the
following session:
(Press Restart)
diary ('session1.txt') <return>
A = [1. 2. 3.; 2. 3. 1.; 3. 2. 1.];b=[5; 4; -1.];<return>
A <return>
b <return>
x = linsolve(A,b) <return>

2001 - Gilberto E. Urroz


All rights reserved

diary(0) <return>

Next, use NOTEPAD, or other text editor, to open the file session1.txt to see the contents
of the file. The default directory for storing a diary file is the bin subdirectory within the
SCILAB directory.
Note: The SCILAB worksheet does not allow cutting and pasting. Therefore, the use of the
diary function with a filename is the only way to copy SCILAB output into a text file.
Command Input: you can read SCILAB commands from a script file, which is basically a
text file listing all the commands you want to use. As an example, create the following
text file in the bin subdirectory of the SCILAB directory using NOTEPAD, and call it
session2.txt:
//-------------------------------------------------------------------------clear
A = [1. 2. -3.
// entering
3. 4. 5.
// elements of
7. 8. 9.]
// matrix A
b = [1.; 2.; 3.]
// enter vector b
xa = inv(A)*b
// calculate x using matrix inverse
xb = linsolve(A,b)
// calculate x using SCILAB's own linsolve function
//--------------------------------------------------------------------------

Then, press Restart in SCILAB, and type: exec('session2.txt')


You will see SCILAB execute all the commands in your file, stopping at the end of the file.

SCILAB command history


All commands entered in a given SCILAB session get stored into a SCILAB command history
buffer.
The commands are thus accessible for re-use or edition.
All the command
history functions are available through the option History under the File menu in the
SCILAB worksheet. The most useful commands are cntl-P and cntl-N, which lets you access
the previous command or the next command, respectively, in the command history buffer.
Once a command is recalled from the command history buffer it can be edited by using the
backspace or delete keys, or by inserting new characters by simply typing at the proper
location.
For example, try the following SCILAB session:
1 - Press the Restart option in the menu bar to clear the SCILAB environment.
2 - Enter the following commands (you dont need to enter the comments):
-->x = [0:%pi/20:2*%pi];
-->y = sin(x) + sin(2*x);

3 - Use cntl-P and edit the previous command (y = sin(x) + sin(2*x);) to read:
-->z = sin(x) + cos(x);

2001 - Gilberto E. Urroz


All rights reserved

4 - Use cntl-P once more to edit the previous command (z = sin(x) + cos(x); ) to read:
-->p = cos(x) + cos(2*x);

5 - So far you have created vectors x, y, z, and p. Next, we use the functions xset with the
option window, and the function plot to produce a plot of y-vs.-x:
-->xset('window',0); plot(x,y)

6 - Use cntl-P to edit the previous command to read:


-->xset('window',1); plot(x,z)

7 - Continue using cntl-P to edit the last commands and produce the following plots:
-->xset('window',2); plot(x,p)
-->xset('window',3); plot(y,z)
-->xset('window',4); plot(y,p)
-->xset('window',5); plot(z,p)

Selective worksheet output


Suppose you have been working on a lengthy SCILAB session whose command history buffer
contains some results that produced errors as well as some intermediary results that are
not of interest to you for output. For your output, you can select only those commands
relevant to your final results by using Cntl-P and Cntl-N. Try the following SCILAB session
that explores some basic vector operations using vectors x and y:
1 - Press the Restart option in the menu bar.
2 - Enter the following SCILAB commands:
-->x = [1, 2, 5, -4]
x =
!

1.

2.

5.

- 4. !

-->y = [0, 2, 3,-5]


y =
!

0.

2.

3.

- 5. !

-->x*y
!--error
10
inconsistent multiplication

-->x.*y
ans =
!

0.

4.

15.

20. !

2001 - Gilberto E. Urroz


All rights reserved

-->sum(ans)
ans =
39.
-->sum(x.*y)
ans =
39.
-->x*y'
ans =
39.
-->x'*y
ans =
!
!
!
!

0.
0.
0.
0.

2.
4.
10.
- 8.

3.
6.
15.
- 12.

- 5.
- 10.
- 25.
20.

!
!
!
!

0.
4.
6.
- 10.

0.
10.
15.
- 25.

0.
- 8.
- 12.
20.

!
!
!
!

-->y'*x
ans =
!
!
!
! -

0.
2.
3.
5.

-->x*y' + y'*x
ans =
!
!
!
!

39.
41.
42.
34.

39.
43.
45.
29.

39.
49.
54.
14.

39.
31.
27.
59.

!
!
!
!

39.
49.
54.
14.

39.
31.
27.
59.

!
!
!
!

-->b = x*y' + y'*x


b =
!
!
!
!

39.
41.
42.
34.

39.
43.
45.
29.

Note: These commands and their corresponding results represent an exploratory session for
vector operations.
3 - Suppose that you are only interested in the commands defining vectors x and y, in the
operations that produce the dot product of the vectors (i.e., sum(x.*y) and x*y'), and in
the very last command (b = x*y' + y'*x). Using the diary command create the file
c:\myVectors.txt and collect only the commands of interest out of the command history
buffer by using cntl-P and cntl-N as needed. The resulting SCILAB session should look like
this:

2001 - Gilberto E. Urroz


All rights reserved

--> diary(c:\myVectors)
-->x = [1, 2, 5, -4]
x =
!

1.

2.

5.

- 4. !

-->y = [0, 2, 3,-5]


y =
!

0.

2.

3.

- 5. !

-->sum(x.*y)
ans =
39.
-->x*y'
ans =
39.
-->b = x*y' + y'*x
b =
!
!
!
!

39.
41.
42.
34.

39.
43.
45.
29.

39.
49.
54.
14.

39.
31.
27.
59.

!
!
!
!

-->diary(0)

The session, except for the very first command () is stored in file c:\myVectors.txt. This
file can be edited or printed from a text editor such as NOTEPAD, or my favorite, PFE
(Programmers File Editor) available for free from:
http://www.lancs.ac.uk/people/cpaap/pfe

The PFE software


PFE is a text editor designed for text-based programming in languages such as FORTRAN,
JAVA, C++, etc. PFE allows the user direct access to DOS windows for compilation and
testing of programs, runs DOS commands from the PFE interface, allows recording and
playing of Macro commands, and permits easy navigation of files by allowing line
numbering for easy debugging of programs.
PFE can be used in combination with SCILAB to type scripts and function files or to edit
diary files produced from within SCILAB.

10

2001 - Gilberto E. Urroz


All rights reserved

Current directory / creating a work directory


SCILAB uses a current directory where files are saved by default, for example when using
the function diary. To see the current directory use:
-->pwd

Under a Windows operating system, the default current directory is typically c:\
The command pwd stands for print working directory.
I recommend that you create a sub-directory, or folder, called work and locate it under the
SCILAB main directory. For example, under a Windows operating system, the SCILAB main
directory will typically be
c:\Program Files\SCILAB2.5
Thus, your work directory would correspond to:
c:\Program Files\SCILAB2.5\work
At the beginning of a SCILAB session, you can change the current directory to the work
directory by using the function chdir:
--> chdir(c:\Program Files\SCILAB2.5\work)

You can use your work directory to store scripts and functions that you create. For
example, if you create a script called script1 in the work directory, once you change the
current directory to the work directory, you can simply use:
-->exec(script1)

to run your script.


If you type a function called function1 in the work directory, with the work directory
selected as the current directory, you can load the function by simply using:
-->getf(function1)

Scripts and function files can be created using NOTEPAD, PDE, or any other text editor.

A preview of SCILAB functions


Here are some useful functions in SCILAB that we will explore in more details in
subsequent chapters:

Elementary functions: sum, prod, sqrt, diag, cos, max, round, sign, fft
Sorting: sort, sortup, gsort, find

Specific matrices: zeros, eye, ones, matrix, empty

11

2001 - Gilberto E. Urroz


All rights reserved

Linear algebra: det, inv, qr, svd, bdiag, spec, schur, trace
Polynomials: poly, roots, coeff, horner, clean, freq
Random numbers: rand
Programming: function, deff, argn, for, if, end, while, select, warning,
error, break, return

Comparison symbols: ==, >=, >, <=, <, =, & (and), | (or)
Execution of a file: exec
Debugging: pause, return, abort
Spline functions, interpolation: splin, interp, interpln
Character strings: string, part, evstr, execstr
Graphics: plot, xset, driver, plot2d, xgrid, locate, plot3d, Graphics
Ordinary differential equation solvers: ode, dassl, dassrt, odedc

To find out more about these functions use the help command. For example, try:
-->help roots
-->help eye
-->help trace

Exercises
Determine the result of the following calculations using SCILAB if a = 2.3, b = -2.3, c= /2, x =
2/, and y = 3:
[1]. (a2 + bc + x)
[2]. sin(c) + y/c
[3]. (a+c)/(x+y)
[4]. 1/(cos(c) + ln(x))
[5]. (a+c)3/b
Check if the following Boolean statements are true or false based on the values of a, b, c, x,
and y given above.
[6]. a > c
[7]. a = b
[8]. (2a+b)/x2 < 1
[9]. x + 2ab + b2 23
[10]. 2ac = 2cb
[11]. Use SCILABs help facility to find out information about function deff and use it to define
a function y = f(x) = x2 + 1.
Using the vectors u = [3, 2, -1], and v = [4, -6, 2], calculate the following operations:
[12]. w = u+v

12

2001 - Gilberto E. Urroz


All rights reserved

[13]. r = u./v
[14]. z = v*u
[15]. t = v.*u
Using the matrices A, B, and C, shown below, perform the following operations:

5 5 2
5 4
2 5

A = 1 2 0 , B = 1 1 10 , C = 1 3
4 1 2
0
4 2
4 2
[16].
[17].
[18].
[19].
[20].

A+B
AB
BA
BC
A BC

13

2001 - Gilberto E. Urroz


All rights reserved

14

2001 - Gilberto E. Urroz


All rights reserved

Summary of SCILAB concepts and commands from Chapters 1-5 in Textbook


1 - Introduction to SCILAB

To download software, get documentation, or visit the INRIA web site find links at:
http://www.engineering.usu.edu/cee/faculty/gurro/SCILAB

-->
SCILAB prompt:
Pre-defined constants: %e, %i, %pi, %eps, %inf, %nan, %t, %f, %s, %z, %io
--> who
: to see active variables in your current SCILAB session
Important options in the Edit menu:
o Copy to clipboard: select text from workspace, click this option to copy text
o Paste: paste text in clipboard to SCILAB workspace
Restart: under the Control menu, clears all variables in current SCILAB session
Demos menu: collection of demonstrations of SCILAB applications
Help > Help Dialog: produces help window for most SCILAB functions
--> help function_name
To find help on a specific function use:
The colon operator: used to create a row vector of data, general form:

vector_name = starting_value : increment : ending_value

To suppress output from a SCILAB command, end the command with a semi-colon (;)
To obtain the transpose of a vector or matrix type the vector/matrix name followed by
an apostrophe, e.g., --> u
--> diary(output_filename)
To start storing a SCILAB session into a file use:
To end session listing use:
--> diary(0)
To navigate through the current SCILAB command history use cntl-N (next command) or
cntl-P (previous command).
--> pwd
To see current working directory:
--> chdir(directory_specification)
To change working directory:
SCILAB script: collection of SCILAB commands stored in a text file (created with PFE,
for example).
To run the SCILAB script stored in file script_file use: --> exec(script_file)

2 - SCILAB Programming, IO, and strings

Comparison operators: ==, <, >, <=, >=, <> or ~=


Logical operators:
& (and), | (or), ~ (not)

For loop:

In a single line:
for index = starting_value : increment : end_value, <statements>, end
for index = starting_value : end_value, <statements>, end

In separate lines:
for index = starting_value : increment : end_value

<statements>
end

for index = starting_value : end_value

<statements>
end

While loop:

In a single line:
While condition, <statements>, end

In separate lines:
While condition

<statements>
end

If-then-else construct:

In a single line:
If condition then statement, end
If condition then statement, else statement, end
If condition then statement, elseif condition then statement, else statement, end

In multiple lines:
If condition then

statement
end
If condition then

statement
else

statement
end
If condition then

statement
elseif condition then

statement

else

statement
end

Select-case construct:

In a single line:
Select variable, case n1, statement, case n2, statement, , end

In multiple lines:
Select variable
case n1

statement
case n2

statement

end

Line functions: functions defined in a single line

deff([output_variable(s)] = function_name(input_variable(s)),[output_variable(s) = function


definition(s)])

Note: Square brackets around the output_variables in the first argument of deff indicate that
the output_variables are optional when evaluating the function function_name. Square
brackets in the second argument of deff are only required if more than one function definition
is used.
Examples of definitions:
--> deff([y] = f(x),y = sin(2*x) + exp(x))
--> deff([x,y] = h(r,theta),[x = r*cos(theta),y = r*sin(theta)])

Examples of evaluations:
-->
-->
-->
-->

f(3.5)
m = f(a)
[x1,y1] = h(3,1.25)
[xP,yP] = h(r1,t1)

File functions: functions typed in a file (e.g., using PFE).


o First line in function is: Function [y1,,yn] = function_name(x1,,xm)
o Output values, i.e., y1,,yn, should be defined somewhere in the body of the
file function
o It is recommended that filename has the same name as the function
o You can use the suffix .sci for the function filename
o A function is loaded by using: --> getf(function_filename_spec)
o Example: type the following function and save it to file
c:\myScilab\changecoord.sci
function [x,y] = changecoord(r,theta)
//Converting polar to Cartesian coordinates
x = r*cos(theta);
y = r*sin(theta);
//End of function changecoord

o
o

Load the function by using: -->getf('c:\myScilab\changecoord.sci')


Examples of function evaluation:
--> [x1,y1] = changecoord (3,1.25)
--> [xP,yP] = changecoord (r1,t1)

Line continuation: If it is necessary to break a command into more than one line,
place the continuation characters (...) at the end of the lines to be continued, e.g.,

--> deff([x,y,z] = spherical(rho,theta,phi), ...


[x = rho*sin(phi)*cos(theta), ...
-->
-->
y = rho*sin(phi)*sin(theta), ...
-->
z = rho*cos(phi)])

Global variable: variable defined in the main SCILAB environment


Local variable: variable defined only within a function.
Debugging statements: pause, return, resume, abort, setbpt, delbpt, disbpt

Saving variables into a file: --> save(file_name,list_of_variables)


Loading variables from a file: --> load(file_name)
Unformatted output to screen:
--> print(6,list_of_variables)
--> print(io(2),list_of_variables)

Unformatted output to a file: --> print(filename,list_of_variables)


Creating a new file for output: --> unit_name = file(open, filename,new)
Writing to a file:
--> write(unit_name, list_of_variables, (format))
Formats for writing to a file: they are FORTRAN-style formats, e.g.,
Iw
: i for integer, w = number of characters allowed (width of field)
fw.d
: f for floating-point, w = width of field, d = number of decimals (dw+3)
ew.d : e for floating-point with scientific notation, w = width of field, d = number of
decimals (dw+7)
aw
: a for alphanumeric (i.e., string output), w = width of field
a
: variable-width
Reading from the keyboard: --> [nxm matrix] = read(%io(1),n,m,[format])
Opening a file for input:
--> unit_name = file(open, filename,old)
Reading a matrix from a file: --> nxm_matrix = read(unit_name, n, m)
Rewinding a file:
--> file(rewind, unit_name)
Closing a file:
--> file(close, unit_name)

String
String
o
o
o
o
o
o
o
o
o
o

The variable ans: contains SCILAB most recent result.


To convert small elements to zero: clean(matrix or vector)

concatenation: string1 + string2


functions:
length(string) - length of string
part(string,[n,m]) or part(string,[n1 n2 nm]) - extract part of string
strindex(string, substring) - determine where substring starts
strsubst(string1, substring_to_be_replaced, substring_to_replace)
string(number) - convert number to string
string(n:m:p) - generates vector of strings based on n, m, p
strcat(vector_of_strings, string_to_insert) - insert string in vector
evstr(string) - evaluate SCILAB command in string
execstr(assignment string) - execute assignment string
disp(string) - display string

3 - Graphics with SCILAB

Simplest 2-D plot where x, y are vectors of the same size and dimensions:
--> plot(x,y,[x_caption, y_caption, plot_caption])
--> plot(y,[x_caption, y_caption, plot_caption])

--> errbar(x,y,em,ep)
Including error bars:
--> xgrid(n)
Add grid to plot:
Changing global parameters of a plot: --> xset(choice_name, x1, x2, x3, x4, x5)
xset(auto clear,off)
o xset(auto clear,on)
o xset(background,color)
o xset(colormap,cmap)
o xset(dashes,n)
o xset(default)
o xset(font,font_id,font_size)
o xset(foreground,color)
o xset(line mode,type)
o xset(mark,mark_id,mark_size)
o xset(pattern,value)
o xset(pixmap,flag)
o xset(thickness,value)
o xset(use color,flag)
o xset(viewport,x,y)
o xset(wdim,width, height)
o xset(window,window_number)
o xset(wpos,x,y)
o xset(wresize,flag)
o xset(wshow)
o xset(wwpc)
To change selected parameters with a form use: xset() or xsetm()
To generate a new graphics window:
xset(window, window_number)
To clear current graphics window:
xbasc()
xget()
To find current settings use:
The plot2d command: plot2d(x,y,[style,strf,leg,rect,nax])
o x,y = matrices of size [nl,nc], nl = number of points, nc = number

o
o

o
o
o

of curves.
style = vector of size [1,nc] to determine the
strf = xyz
! x = 1, display captions in leg
! y = 1, use rect;
! y = 2, calculate boundaries using xmax and xmin
! y = 3, similar to y = 1 with isoview scaling
! y = 4, similar to y = 2 with isoview scaling
! y = 5, similar to y = 1 but with boundaries with nice
gradations
! y = 6, similar to y = 2 but with boundaries with nice
gradations
! z = 1, axis drawn with specifications from nax
! z = 2, framed plot without grid
! z = other values, no frame produced
leg
= leg1@leg2@
rect = [xmin, ymin, xmax, ymax]
nax
= [nx, Nx, ny, Ny]
where nx,ny = sub-graduations in x,y; Nx,Ny = graduations in x,y.

To place a title in the plot:

xtitle(plot_title)

Plotting with symbols: use negative values for the styles


Defining the grid: plotframe(rect,tics[,arg_opt1,arg_opt2,arg_opt3])
Calculating the grid:
[xi,xa,npx] = graduate(xmi, xma, n1, n2) - default n1,n2 = 3,10
[xi,xa,npx] = graduate(xmi, xma)
Use it to define rect = [xi,yi,xa,ya] and nax = [nx,npx,ny,npy]

Other two dimensional plot commands:


o plot2d1: piecewise linear curves with possible logarithmic scales
o plot2d2: piecewise constant (stepped) curves
o plot2d3: vertical bars
o plot2d4: arrows style (for ODEs in phase space)
General form of previoius commands: plot2di(str,x,y[,style,strf,leg,rect,nax])
Where str = abc. If a = e, values of x are not used. If a = 0, x values are the same
for each curve. If b = l logarithmic scale is used in x. If c = l logarithmic scale is
used in y.

Histograms: histplot(npoint,data,[style,strf,leg,rect,nax])
where npoint = number or vector of classes, data = vector.

Creating sub-windows: xsetech(wrect[,frect,logflag])


where wrect = vector of size 4 (sub-window definition, e.g., [0.,0.,0.5,0.5], frect =
vector of size 4, logflag = string of the form xy, where x and y can be n(normal) or
l(logarithmic).

Modifying plot properties:


o xgrid(style): adds grid to 2-D plot
o xtitle(title,xlabel,ylabel): adds title, axes label and/or frame
o titlepage(string): title page in middel of plot
o xclea(x,y,w,h): clears area with upper left corner (x,y) of dimensions w x h
o xstring(x,y,str[,angle,flag]): draws string starting at point (x,y)

To
To
To
To

store a plot as a pixmap: xset(pixmap,1)


recall pixmap to screen: xset(wshow)
clear the pixmap:
xset(wwpc)
animate a plot of a function f(x,j) for different values of j:

xbasc(); x = [xmin:incr:xmax];
for j=1:nfigs, y = f(x,j); plot2d(x,y); xset(wshow); xset(wwpc); end

Color map = m x 3 matrix (m = number of colors available, default m = 32).


Color number i defined as cmap(i,1), cmap(i,2), cmap(i,3), corresponding to red,
green, blue intensities between 0 and 1.
To set the colormap use xset(colormap,cmap), where cmap = color map matrix.
To obtain a colormap with n colors, use: cmap = hotcolormap(n)

Density plots: grayplot(x,y,z[,strf,rect,nax])


where x has size [n1,1], y has size [n2,1], and z has size [n1,n2], with z(i,j) =
f(x(i),y(j)).
Density plot in grayscale, use the following, before calling grayplot:

Smooth density plots: use function Sgrayplot instead of grayplot.

R = [1:256]/256; cmap = [R,R,R]; xset(colormap,cmap);

Color map of a matrix: Matplot(a[,strf,rect,nax])

Plotting a function of the form y = f(x): fplot2d(x,f)

Plotting a function of the form z = f(x,y) using grayscale:


fgrayplot(x,y,f[,strf,rect,nax])

Smooth grayscale function plot: Sfgrayplot(x,y,f[,strf,rect,nax])

Plotting a vector field in the plane: champ(x,y,fx,fy[,arfact,rect,strf])


where fx(i,j) = fx(x(i),y(j), and fy(i,j) = fy(x(i),y(j); arfact = scale factor for arrow
heads (default = 1.0), rect and strf = xyz are similar to command plot2d.

Direction field vector plot for ODE: fchamp(f,t,x,y[,arfact,rect,strf])


where dx/dt = f(t,x), t = fixed value, x,y = vectors.

Plotting data in three-dimensions:


o

plot3d(x,y,z[,theta,alpha,leg,flag,ebox])

o plot3d(xf,yf,zf[,theta,alpha,leg,flag,ebox])
o plot3d(xf,yf,list(zf,colors)[,theta,alpha,leg,flag,ebox])
where theta and alpha are angles (degrees) representing spherical coordinates of
viewpoint; leg represents captions for each axis (e.g., x@y@z); flag =
[mode,type,box], with mode > 0 hidden parts of surface removed, mode = 0 draws
hidden parts, mode < 0 shadow painted; type = 0 uses currend 3D scaling, type = 1
boundaries specified by ebox; box = 0 or 1, no frame is drawn, box = 2, only axes
behind surface drawn, box = 3, box and captions added, box = 4, box, caption and
axes added; ebox (used if box = 1) = [xmin, xmax, ymin, ymax, zmin, zmax].
If using xf, yf, zf plot3d draws the facets defined by those matrices where
coordinates of i-th facet are given by xf(:,i), yf(:,i), zf(:,i).

Obtaining facet information: [xf,yf,zf] = genfac3d(x,y,z[,mask])


where z(i,j) = f(x(i),y(j)). The optional argument mask = Boolean matrix used to select
entries of z to be represented by facets.
Obtaining facet information given parametric surface x=x(u,v), y=y(u,v), z=z(u,v), use:
[xf,yf,zf] = eval3dp(fun,u,v)

where z = fun(x,y), u,v = vectors.

Three-dimensional surface plot with color/gray scales:


plot3d1(x,y,z[,theta,alpha,leg,flag,ebox])
plot3d1(xf,yf,zf[,theta,alpha,leg,flag,ebox])

Plotting functions in three-dimensions:


fplot3d(x,y,z[,theta,alpha,leg,flag,ebox])

Grayscale/color scale three-dimensional plot for functions:


fplot3d1(x,y,z[,theta,alpha,leg,flag,ebox])

Parametric curves in space: param3d(x,y,z[,theta,alpha,leg,flag,ebox])

Plotting multiple parametric curves in space:


param3d1(x,y,z[,theta,alpha,leg,flag,ebox])
param3d1(x,y,list(z,colors)[,theta,alpha,leg,flag,ebox])

Contour plots in the plane and space:


contour(x,y,z,nz[,theta,alpha,leg,flag,ebox,zlev])

where x (size = n1), y (size = n2), z (size = n1,n2), nz = number or vector, theta, alpha,
leg, flag, ebox are as defined before, and, if mode = 1, curves are drawn on a 3-D plot
and on the plane z = zlev.

Contour plots in the plane only: contour2d(x,y,z,nz[,style,strf,leg,rect,nax])

Contour plots given z = f(x,y):


fcontour(x,y,f,nz[,theta,alpha,leg,flag,ebox,zlev])

Contour plots in a plane given z = f(x,y):


fcontour2d(x,y,f,nz[,style,strf,leg,rect,nax])

Three dimensional histogram:


hist3d(f[,theta,alpha,leg,flag,ebox])
hist3d(list(f(x,y,z)[,theta,alpha,leg,flag,ebox])

Note: you need to provide the frequency count f before plotting.

Animation of three-dimensional graph: use xset(wshow) and xset(wwpc) as in 2-D.


(See example in page 73 of textbook)

Combination of two- and three-dimensional plots: (see examples in pages 73 and 74).

For a listing of graphics problems see pages 74-77 in textbook.

4 Vectors

Vector magnitude: norm(vector)


Minimum and maximum values of a vector: min(vector) max(vector)
Dot product of two row vectors: u*v
Dot product of two column vectors: u*v
Cross-product function (see pp. 90-91)
Term by term operations: use the dot before the operation (e.g., .* ./)
Examples of vector operations pp. 94-111

5 Matrices and Linear Algebra

Transpose of a matrix/vector: use the apostrophe after object name, e.g., A


Inverse of a matrix: inv(matrix)
Identity matrix: eye(n,n) or eye(A)
Vandermonde function: see pp.130-131
Hilbert matrix: testmatrix(hilb,n)
Magic squares: testmatrix(magic,n)
Trace: trace(matrix)
Dimensions of a matrix/vector: size(matrix)
Random-elements matrix: rand(n,m) or rand(A)
Extracting rows: A(1,:), A(2,:)
Extracting columns: A(:,1), A(:,2)
Adding row vectors to a row vector:
rv = [], rv = [rv r1], rv = [rv r2]
Adding columns to a matrix from row vectors: B = [], B = [B;r1], B = [B;r2]
Adding columns to a matrix from column vectors: B = [], B = [B c1], B = [B c2]

Adding column vectors to a column vector: cv = [], cv = [cv c1], cv = [cv c2]
Sums and products of all elements of a matrix: sum(B), prod(B)
Sums and products by columns (to produce a row sum/product): sum(B,r),
prod(B,r)

Sums and products by rows (to produce a column sum/product): sum(B,c),


prod(B,c)

Solution to linear system Ax+c = 0: [x0,nsA] = linsolve(A,c[,x0])

Least-square methods to force a solution of f(x) = Ax+c, with derivative g(x) = f(x) =
A:
--> deff(y = f(x,A,c),y = A*x + c)
--> deff(yp = g(x,A,c),yp = A)
--> [SSE,xsol] = leastsq(f,g,x0)

or use function Lslinsolve described in pp. 149-150

Solution to linear system Ax = b using left division: --> xsol = A\b

LU factorization: [L,U] = lu(A)

or

[L,U,P] = lu(A)

Singular-value decomposition (see pp. 156-158):


[U,S,V] = svd(A)
[s] = svd(A)
[U,S,V,r] = svd(A,tol)

Rank of a matrix: rank(matrix)

Norms
o
o
o
o

of a matrix:
norm(A) or norm(A,2)

Norms
o
o
o

of a vector
norm(v) or norm(v,2)

norm(A,1)
norm(A,inf) or norm(A,%if)
norm(A,fro)

: Euclidean norm
: L1-norm or column norm
: Infinity norm
: Frobenius norm
: Euclidean norm
: Lp-norm
: Infinity norm

norm(v,p)
norm(v,inf)

Condition number of a matrix: cond(matrix)


Determinant of a matrix: det(matrix)
Gaussian elimination user-defined functions:
o gausselim:
Nave Gaussian elimination, pp.177-178
o gausselimPP: Gaussian elimination with partial pivoting, pp. 181
o gausselimmm: Gaussian elimination for multiple sets of equations, pp. 183184
o gausselimd: Gaussian elimination used to calculate determinant, pp. 185186

To obtain eigenvalues of a matrix: spec(matrix)


User-defined function for eigenvectors see pp. 193-194
User-defined function for generating the characteristic equation see pp. 196
User-defined function for generalized eigenvectors pp. 197

Sparse matrices:
o
o
o
o
o
o
o
o
o

Define a sparse matrix: sparse(matrix) or sparse(index,values)


Convert sparse to full: full(matrix)
To get information about sparse matrix:
[index,val,dim] = spget(sparse_matrix)
Sparse matrix with ones: spones(A)
Sparse identity matrix: speye(n,n)
Random-element sparse matrix: sprand(n,m,density)
Sparse matrix with zero entries: spzeros(A) or spzeros(n,m)

User-defined function to visualize sparse matrices p. 204


Factorization of sparse matrices, use:
[hand,rk] = lufact(As)
[P,L,U,Q] = luget(hand)
ludel(hand)

Solution of linear system (Ax = b) using sparse matrices:


x = lusolve(hand,b)
ludel(hand)

Solution of linear systems can be obtained using inverses or left-division also.

User-defined function for solution of linear systems with tri-diagonal matrix of


coefficients pp.209-211
Solution of tri-diagonal system of linear equations using sparse matrices pp. 211-213

Iterative solutions of systems of linear equations pp. 213-215

Matrix
o
o
o
o
o
o
o

applications:
Electric circuits pp. 216-218
Structural mechanics pp. 218-221
Dimensionless numbers in fluid mechanics pp. 221-224
Stress at a point in a solid in equilibrium pp. 225-230
Principal stresses at a point pp. 230-231
Multiple linear fitting of data pp. 232-234
Polynomial fitting (user-defined function) pp. 234-241

10

Summary of Chapter 8 - Data fitting and interpolation


Simple linear interpolation
Given { (x i,yi),i = 1,2,,n }, and x k such that x i < xk < xk+1, then yk = yi + (xk -xi)(yi+1 -yi)/(xi+1-x i).
Entering the table as the matrix:

--> xy_table = [x1,x2,,xn;y1,y2,,y n]

you can use SCILAB function interpln to obtain yk , given xk : --> yk = interpln(xy_table,xk)
Polynomials in SCILAB

To define variable s as a polynomial use:


--> s = poly(0,s)
To identify the variable in a polynomial p use:
--> varn(p)
To determine the degree of a polynomial p use:
--> degree(p)
To obtain a vector with the coefficients of a polynomial p (increasing degree of
independent variable, from degree zero to n)
--> coeff(p)
Simple operations on polynomials p and q on the same independent variables:
o Addition:
p+q
o Subtraction:
p-q
o Multiplication: p * q
o Division:
p/q
o Power:
p^n
Division providing quotient (quo) and residual (res):
--> [res,quo] = pdiv(p,q)
Polynomial long division that generates n coefficients of the expansion p/q:
--> ldiv(p,q,n)

Polynomial fractions, say, p = n/d


o To get numerator and denominator of p:
--> numer(p), denom(p)
o To simplify a polynomial fraction
--> simp(n,d)
Matrices with polynomial elements
o Defined as other SCILAB matrices
o Determinant: --> det(A)
o Inverse: --> inv(A)
o Inverse components A-1 = N s /d:
--> [Ns,d] = coffg(A)
Evaluating a polynomial or polynomial matrix, p(x)|x=a : --> horner(p,a)
Derivatives of a polynomial p:
--> derivat(p)
To generate polynomial pn (x) = a0+a1x+a2x 2++anxn , given its coefficients:
--> a = [a0,a1,a2, , an]
--> p = poly(a,x,coeff)
or
--> p = poly([a0,a1,,an],x,coeff)
To generate a polynomial pn (x) = (x-r1)(x-r2), given its roots:
--> r = [r1 r2 ]
--> p = poly(r,x)
--> p = poly([r1,r2,],x)

or --> p = poly(r,x,roots) or
or --> p = poly([r1,r2,],x,roots)
To find the roots of a polynomial use: --> roots(p)
Indefinite integrals of polynomials - use function intpoly (see pp. 398-399):
--> intpoly(p)

Numerica l Methods with Polynomials


Polynomial deflation (see examples in pp. 399-401). Use relationship:
Pn (x) = (x-r)Qn -1(x) + R, with Pn (r) = R, and Pn (r) = Qn -1(r). With SCILAB:
--> x = poly(0,x), Rnm1 = horner(Pn,r), dn = x - r
--> [Rnm1,Qnm1]=pdiv(Pn,dn),Pnp=horner(Qnm1,r)

Direct fitting of a polynomial: fit an n-order polynomial to a set of n+1 data points. Use
function dfp, pages 401-402.
Lagrange polynomials: Use function LagPol, pages 402-405.
SCILAB function mtlb_diff: see pages 405-407 -- Used in difference tables (see below).
Difference tables: use function Difference_Table, pages 407-411
Newton Forward-Difference Polynomial: use function NFDP, pages 411-413
Newton Backward-Difference Polynomial: use function NBDP, pages 413-415
Stirling centered-difference polynomial: use function stirling, pages 415-418
Bessel centered-difference polynomial: use function bessel, pages 418-420
Least-Square Polynomial Approximation: use function PolyFit, pages 420-424
o Linear Data Fitting, pages 422-423
o Other Linearized Data Fittings, pages 423-425

Interpolation with splines

Cubic splines: fitting n-1 cubic polynomials, y = fk (x) = b0+b1x+b2x2+b3x 3, through the
data set [(x i,yi), i = 1,2,,n], requiring that the functions fk (x), and their first and
second derivatives, s=fk (x) [slope], = fk (x) [curvature], be continuous at the interior
points (x i,yi), i = 2,3,,n-1. Options for conditions at extreme points (x 1,y1), (xn ,yn )
are: [1] fixed slope values, f1(x1) = h1, fn -1(xn) = hn ; [2] Zero curvature, f1(x1) = fn1 (x n) = 0; [3] Linear extrapolation of curvatures, 1 = fct(2 ,3 ), n = fct(n-2 , n-1 ); [4]
Third derivative continuous at x2 and xn-1, f1(x2) = f2(x 2), fn-2(xn-1) = fn-1(xn-1).
This makes the fitted function periodic.

SCILAB functions for cubic splines


o Given vectors of data x and y, function splin returns the vector of derivatives
of the fitted splines d. The option periodic is optional (case [4], above):
--> d = splin(x,y[,periodic])

o To obtain vectors of the cubic spline fitting y0, and its first three derivatives,
y1, y2, y3, for a vector xd, whose elements are in the interval defined by x,
use function interp:
--> [y0,y1,y2,y3] = interp(xd,x,y,d)

o To obtain the fitting for the values of x, use function smooth. This function

requires a matrix xy_Original_Table = [x;y], and an increment for x-values, x,


and returns a matrix xy_Fitted_Table. Steps for obtaining and plotting fitting
given vectors x and y:
-->
-->
-->
-->
-->
-->
-->

xy_Original_Table = [x;y]
xy_Fitted_Table = [xy_Original_Table, Dx]
xx = xy_Fitted_Table(1,:), yy = xy_Fitted_Table(2,:)
min(xx), max(xx), min(yy), max(yy) //Use these values to
rect = [xmin, ymin, xmax, ymax]
//
set up plot rectangle
plot2d(x,y,-9,011, ,rect)
//Plot original points
plot2d(xx,yy,1,011, ,rect)
//Plot fitted splines

User-defined functions for cubic splines


o Function splinepol (pages 431-435) can be used to produce a vector ps
containing the n-1 cubic splines from the data set defined by the vectors x and
y (both of size n). It requires the vector of derivatives d obtained from using
SCILAB function splin (see above), as well as the independent variable to be
used in the polynomial var. The call to the function is
--> ps = splinepol(x,y,d,var)

o Function intersplin (pages, 431-435) produces a vector of values yy

corresponding to the evaluation of the polynomials in ps (obtained with


splinepol -- see above) for the values of the independent variable contained in
vector xx. The function requires the original vector x as input also. The call to
the function is:
--> yy = intersplin(xx,x,ps)

Multi-variate data fitting


Some approaches:
Succesive univariate polynomial interpolation: Given a table of zij = f(xi ,yj), find z* =
f(x*,y*), such that xi < x* < xi+1 , yj < y* < yj+1. See details and examples in pages 436439.
Direct multivariate polynomial fitting: Generalization of direct univariate polynomial
shown earlier. See pages 439-440 for an example.
Least-square multivariate polynomial fitting:
o Multivariate linear example: pages 440-443
o Bivariate quadratic fitting example: pages 443-445
SCILAB function datafit
Use this function to obtain the m parameters p = [p1,p2,,pm] of a model h = f(p,r), with n
independent variables r =[r1,r2,,rn ], given the data set {((r1)i, (r2)i, (rn )i, h) (ri,hi), i = 1,2,
,k}. It is necessary to build an error function e = G(p,z) = h - f(p,r), where the components of
vector z = [z 1,z2,,zn ,zn+1 ] = [r1,r2,,rn ,h], represent all variables involved, i.e., r and h.
Examples of error function definition for using datafit:
[1]. y = p1 + p2 exp(p3x), h = y, m = 3, r = x, p = [p1;p2;p3], z = [x;y], i.e., x = z1, y = z2:
--> deff([e]=G(p,z),e=z(2)-(p(1)+p(2)*exp(p(3)*z(1)))))

[2]. q = p1 + p2x + p3y + p4x 2 + p5xy + p6y2, h = q, m = 6, r = [x;y], z = [x;y;q], i.e., x = z1, y = z2,
q = z3:
--> deff([e] = G(p,z), ...
--> G(p,z)= ...
--> z(3)-(p(1)+p(2)*z(1)+p(3)*z(2)+p(4)*z(1)^2+p(5)*z(1)*z(2)+p(6)*z(2)^2))

It is also necessary to build a matrix Z(n+1) k whose rows consists of the k values given for the n
independent and the one dependent variables, i.e.,

r1 ( r1 )1
r ( r )
2 2 1
Z= M= M

rn ( rn )1
h h1

( r1 ) 2
( r2 ) 2
M
( rn ) 2
h2

L ( r1 ) k
L (r2 ) k
O
M

L (rn ) k
L hk

A simple call to function datafit is the following:


--> [p,err] = datafit(G,Z,p0)

where p0 is a column vector of m rows providing an initial guess for the parameters of the
model, p is the column vector containing the m parameters, and err is the sum of squared
errors (a measure of the goodness of fitting of the data).
It is also possible to include a vector of m derivatives s = [G/p1, G/p2, ,G/pm ], defined
as a function, in the call to function datafit. E.g., for the function y = p1 + p2 exp(p3x),
--> deff([s]=DG(p,z), s=[-1,-exp(p(3)*z(1)),-a(2)*z(1).*exp(p(3).*z(1))])

The call to datafit is now:


--> [p,err] = datafit(G,DG,Z,p0)

Summary of Chapter 9 - Ordinary Differential Equations (ODEs)


Introduction (definitions)

Ordinary and partial differential equations - page 459


Order and degree of an equation - page 459
Linear and non-linear equations - pages 459-460
Constant or variable coefficients - page 460
Homogeneous and non-homogeneous equations - page 460
Solutions - pages 461-463
o General and particular solutions - pages 461- 462
o Verifying solutions using SCILAB - page 462
o Initial and boundary conditions - pages 462-463

Symbolic solutions to ODEs

Solution techniques for 1st -order, linear ODEs with constant coefficients - pp. 463-466
o Equations of the form dy/dx = f(x) - direct integration - pp. 463-464
o Equations of the form dy/dx = g(y) - inversion and direct integration - p. 464
o Equations of the form dy/dx = f(x)g(y) - separation of variables - p. 465
o Equations of the form yd/dx = g(y/x) - pp. 465
o Equations of the form a(dy/dx) + by = f(x) - Integrating factors - pp. 465-466
Integrating factors for 1st -order, linear ODEs with variable coefficients - p. 466
Exact differential equations - pp. 466-467
Solution of homogeneous linear equations with constant coefficients - pp. 467-469
Particular solution for 2nd-order, linear ODE with constant coefficients - pp. 469-472

Applications of ODEs I: analysis of damped and undamped free oscillations - pp. 472-479
Phase portraits of oscillatory motion - pp. 477-479
Applications of ODEs II: analysis of damped and undamped forced oscillations - pp. 479-482
Applications of ODEs III: oscillations in electric circuits - pp. 483-484
Finite differences and numerical solutions

Finite differences - pp. 485-486


Finite difference formulas based on Taylor series expansions - p. 487
Forward, backward and centered finite difference approximations for the 1st -derivative
- pp. 487-488

f ( x 0 + h) f ( x0 )
df
=
+ ( h)
dx
h
f ( x 0 ) f ( x 0 h)
df
=
+ (h )
dx
h
f ( x 0 + h ) f ( x0 h )
df
=
+ ( h 2 )
dx
2 h

Forward, backward and centered finite difference approximations for the 2nd-derivative
- pp. 488-489

f ( x 0 + 2 h) 2 f ( x0 + h) + f ( x 0 )
d2 f
=
+ ( h)
2
dx
h2
f ( x 0 ) 2 f ( x0 h) + f ( x0 2 h)
d2 f
=
+ ( h)
2
dx
h2
f ( x 0 + h) 2 f ( x 0 ) + f ( x 0 )
d2 f
=
+ ( h 2 )
2
dx
h2

Solution of a 1st -order ODE using finite differences - Euler forward method - pp. 489494 (see function Euler1 - p. 491)
Finite difference formulas using indexed variables - pp. 494-495
o

First derivative
Backward,

dy/dx = ( yi+1-yi)/x + O(x)

Centered,

dy/dx = (yi+1-yi-1)/(2x) + O(x)2

Forward,

dy/dx = (yi+1-yi)/x + O(x)

Second derivative
Backward,

d2y/dx 2 = (yi+2-2yi+1+yi)/(x)2 + O(x)

Centered,

d2y/dx 2 = (yi+1-2yi+yi-1)/(x)2 + O(x)2

Forward,

d2y/dx 2 = (yi-2yi-1+yi-2)/(x)2 + O(x)

Solution of a 1st -order ODE using finite differences - an implicit method - pp. 495-498
Explicit vs. implicit methods - p. 498
Outline of explicit solution for a 2nd-order ODE - pp. 498-499
Outline of the implicit solution for a 2nd-order ODE - pp. 499-500

Systems of ODEs
Systems of ODEs using matrices - pp.500-501
Systems of linear homogeneous ODEs - solution using matrices - pp. 501-505
Systems of linear nonhomogeneous ODEs - solution using matrices - pp. 505-506
Converting 2nd-order linear equations to a system of equations - pp. 506-508
Formula for converting an n-th order linear ODE with constant coefficients into a linear
system of ODEs:
dn y/dx n + an -1(dn -1y/dx n -1) + + a2(d2y/dx 2) + a1(dy/dx) +a0y = r(x)
Re-write it as:
dn y/dx n = - an-1(dn -1y/dx n -1) - - a2(d2y/dx 2) - a1(dy/dx) -a0y + r(x)

The resulting system of linear equations is:


dun -1/dx = - an -1un -1 - an -2un -2 - - a2u2 - a1u1 -a0y + r(x)
dun -2/dx = un -3, dun -3/dx = un -2, , du1/dx = u2, dy/dx = u1,
In matrix form,
df/dx = Af(x) + g(x)
where

u n 1 ( x)
u ( x )
n 2
M
f ( x) =
, A =
u 2 ( x)
u1 ( x )

y( x)

a n 1
1

0
M

a n 2
0
1
0
M
0

a n 3
0
0
1
M
0

L a1
L 0
L 0
L 0
O
M
L 1

a0
r(x )

0
0

M
0
, g( x) =
.
0
0
0
M

0
0

SCILAB functions for the numerical solutions of initial value problems (IVPs)

Function ode (pp. 509-511): Given the ODE dy/dx = f(x,y), with initial conditions
(x0,y0), find the solution y(x) for a vector of values of x,
--> y = ode(y0,x0,x,f)

Also, given the ODE system, dy/dx = f(x,y), with initial conditions (x0,y0), find the
solution y(x) for a vector of values of x (Note: y = [y1,y2,,yn ], f(x,y) = [f1(x,y), f2(x,y),
,fn (x,y)]):
--> y = ode(y0,x0,x,f)

Numerical methods used in function ode - general call to ode (pp. 511-513):
--> [y] = ode([type],y0,x0,x,f)

optional argument type can be adams, stiff, rk, rkf, fix, discrete, roots
o Adams-Bashforth methods - p. 512
o Adams-Moulton methods - p. 512
o Adams-Bashforth-Moulton methods - p. 512
o Runge-Kutta methods - p. 513
o Examples of function ode with different numerical methods - pp. 514-516
Stiff ODEs - pp. 516-518
Function ode with root finding option - pp. 519-520
Discrete solutions with function ode - p. 520
Changing ODE numerical solution parameters with odeoptions - pp. 521-522

Applications of numerical solutions to IVPs

Systems of ODEs from mechanical systems - pp. 522-525


Systems of ODEs from electric circuits - pp. 526-530
Solving a fourth-order equation - pp. 530-532
The Van der Pol equation - pp. 532-535
The Rssler flow - pp. 535-537

Solutions to boundary value problems (BVPs)

The shooting method - Use function shooting - pp. 538-542


Outline of the implicit solution for a second-order BVP - p. 542
Function bvode for the solution of BVPs - pp. 542-551
o External SCILAB functions used with bvode - pp. 543-544
o General call to function bvode - p. 544
o Description of elements of vector ipar - pp. 544-545
o Application of function bvode to a 2nd-order BVPs - pp. 545- 546
o Function bvode applied to a 3r d-order BVP - pp. 546-548
o Application of bvode to a 3r d-order BVP with one interior fixed point - pp. 548549
o Application of bvode to a 4th-order BVP with two interior fixed points - pp. 550551
BVPs with eigenvalues - pp. 552-556
o Numerical solution to a BVP with eigenvalues - pp. 552- 554
o A function for calculating eigenvalues for a BVP - pp. 554-556

Multiple-defined functions and their evaluation in SCILAB


To evaluate a function defined by multiple expressions, for example,

x 2 , 10 x < 1

1+ x 2 , 1 x < 3

f 00 ( x ) =
,
sin
x
+
cos
2
x
,
3

x
<
10

0, elsewhere
we can write a file function f00 that will look as follows:
===============================
function [y]=f00(x)
if x>=-10 & x<-1 then
y = x^2
elseif x>=-1 & x<3 then
y = sqrt(1+x^2)
elseif x>=3 & x<10 then
y = sin(x) + cos(2*x)
else
y = 0
end
================================

To evaluate the function at a single point we simply use the function name with a single
argument, e.g.,
-->getf('f00.sci')
-->f00(2.5)
ans = 2.6925824

An attempt to evaluate this function for a vector argument returns an error:


-->x = [0:1:3]
x = !
0.

1.

2.

3. !

--> y = f00(x)
!--error
4
undefined variable : y
at line 11 of function f00 called by :

y = f00(x)

To produce a vector out of the intended evaluation we can try the following commands:
-->x = [0:1:3]
x = !
0.

1.

2.

3. !

-->[m n] = size(x)
n = 4.
m = 1.
-->y = []
y = []

-->for j = 1:n,
y =
1.
y = !
1.
y = !
1.
y = !
1.

y = [y f00(x(j))], end
1.4142136 !
1.4142136
1.4142136

2.236068 !
2.236068

1.1012903 !

The output lines shown above correspond to each value of j = 1, 2, 3, and 4. The last line
shows the final value of the vector y.
If you dont want to go through all these steps to evaluate a vector of values of the function,
you can re-write the function to account for the possibility of vector evaluation as follows:
===========================================================
function [y]=f01(x)
//[m n] = size of input variable x and output variable y
[m,n] = size(x)
//Create output vector y and fill it with zeroes
y = zeros(m,n)
//Calculate y(i,j) for each value x(i,j) for
//i = 1 to m, j = 1 to n
for i = 1:m
for j = 1:n
if x(i,j)>=-10 & x(i,j)<-1 then
y(i,j) = x(i,j)^2
elseif x(i,j)>=-1 & x(i,j)<3 then
y(i,j) = sqrt(1+x(i,j)^2)
elseif x>=3 & x<10 then
y(i,j) = sin(x(i,j)) + cos(2*x(i,j))
else
y(i,j) = 0
end
end
end
===========================================================

With this definition, calculating vectors of values of the function is straightforward:


-->getf('f01.sci')
-->x = [0:1:4], y = f01(x)
x = !
0.
1.
2.
y = !
1.
1.4142136

3.
4. !
2.236068

0.

0. !

In summary: if your function is intended to return a vector or matrix, make sure that the
function is written to account for that possibility -- as illustrated in this case.
Notice that the use of indexed variables in the function f01, -- e.g., statements like:
elseif x(i,j)>=-1 & x(i,j)<3 then
y(i,j) = sqrt(1+x(i,j)^2)

-- is necessary here because we need to determine the interval where x(i,j) is located before
evaluating f01.
If the function is defined with a single expression, it is not necessary to use indexed variables,
as illustrated with the following function,

|x|

8.17
+ x2
3.23

f 02 ( x ) =
.
1.23 sin x + 3.21 cos 2 x
The corresponding SCILAB function file f02 is shown next:
==============================================
function [y] = f02(x)
t1 = 8.17*(abs(x)/3.23 + x^2)
t2 = 1.23*sin(x) + 3.21*cos(2*x)
y = t1./t2
==============================================

Notice that the function definition y = t1./t2 includes a term-by-term division (./) to account
for possible vector or matrix argument x.
Evaluation of the function with a vector argument is illustrated next:
-->getf('f02.sci')
-->x = [2:1:6]
x =
!

2.

3.

4.

5.

6. !

-->f02(x)
ans =
! - 38.518429

24.915573

- 100.74785

- 56.003836

130.77576 !

This function f02 can also be defined in the SCILAB window by using the command deff as
follows:
-->deff('[y]=f02(x)','y=8.17*(abs(x)/3.23+x^2)./(1.23*sin(x)+3.21*cos(2*x))')
Warning :redefining function: f02

Notice that we use term-by-term division (./) in this definition to account for possible vector
arguments in the function evaluation.
Evaluating the function with the pre-defined vector x as argument produces the same result as
with the file function f02 used previously:
-->f02(x)
ans =
! - 38.518429

24.915573

- 100.74785

- 56.003836

130.77576 !

Example of a double integral calculation using SCILAB function int2d


Consider the double integral of the function f(x,y) = 1 over the circular region x 2+y2 1.
Because the double integral represents the volume under the function f(x,y) and above the
region of integration, this integral should be equal to = 3.1415. To divide the region into
triangles we use the following function Triangle. This function produces the matrices X and Y
containing the coordinates of the triangles as well as a plot of the triangles themselves.
==================================================================================
function [X,Y] = Triangles(R,n)
//Calculates the coordinates of the n triangles used to approximate a
//circle of radius R. The triangles have a vertex at the origin.
X = zeros(3,n)
Y = X
Dtheta = 2*%pi/n;
for j = 1:n
X(1,j) = 0.0
X(2,j) = clean(R*cos((j-1)*Dtheta))
X(3,j) = clean(R*cos(j*Dtheta))
Y(1,j) = 0.0
Y(2,j) = clean(R*sin((j-1)*Dtheta))
Y(3,j) = clean(R*sin(j*Dtheta))
end
p = ones(1,n)
plot2d(X,Y,p)

=========================================================================
First, we define the function f(x,y) = 1, and load function Triangles:
-->deff('[z]=f(x,y)','z=1')
-->getf('Triangles')

Next, we calculate the triangles and the double integral for 8, 32, and 128 triangles:
-->n=8;[X,Y]=Triangles(1,n);int2d(X,Y,f)
ans = 2.8284271
-->n=32;[X,Y]=Triangles(1,n);int2d(X,Y,f)
ans = 3.1214452
-->n=128;[X,Y]=Triangles(1,n);int2d(X,Y,f)
int2d: termination: function evaluations > MEVALS
ans = 3.1403312

Notice that the last evaluation (for n=128) produces a termination message. It seems to
indicate that we have surpassed the allowed number of function evaluations in the calculation
of the double integral. To understand this message use the SCILAB help command with the
function name int2d:
-->help int2d

To avoid this termination message call function int2d with an additional argument, the vector
[1.e-10,1,200,20000,1] , as shown next:
-->n=128;[X,Y]=Triangles(1,n);int2d(X,Y,f,[1.e-10,1,200,20000,1])
ans = 3.1403312

Although we avoid the termination message we find that the value of the integral is the same
as obtained earlier.
Notice that as n increases from 8 to 32 and 128, the value of the double integral does indeed
approach .
Example of a double integral calculation using user-defined function DoubleIntegral and
SCILAB function int2d
We want to calculate the double integral of the function f(x,y) = x2+y2, on the elliptical region
R described by -5 < x < 5, -(3/5)(25-x 2)1/2 < y < (3/5)(25-x 2)1/2.
The integral to be calculated is

I =

3
25 x2
5
3
5 25 x 2
5
5

( x 2 + y 2 ) dy dx .

The exact value of the integral can be obtained using Maple:


> 'int(int(x^2+y^2,y=-(3/5)*sqrt(25-x^2)..(3/5)*sqrt(25-x^2)),x=-5..5)';II=%;evalf(%);
5

-5

25 x

3/5

x 2 + y2 dy dx

3/5

25 x

II :=

255

400.5530634
The function to be integrated can be defined in SCILAB as:
-->deff('[z]=f(x,y)','z=x^2+y^2')
Transformation of the region R into region R': -5 < x < 5, 0 < z < 1, requires us to define the
following function (x,z):

6
3
6
( x, z ) = ( x 2 + ( z 25 x 2
25 z 2 ) 2 )
25 x 2
5
5
5
-->deff('[p]=psi(x,z)','p = ...
-->(x^2+((6/5)*z*sqrt(25-x^2)-(3/5)*sqrt(25-z^2))^2)*(6/5)*sqrt(25-x^2)')

The integral on the transformed region is

I =

(x

5 0

6
3
6
+ ( z 25 x 2
25 z 2 ) 2 ) 25 x 2 dy dx
5
5
5

Function DoubleIntegral is used to calculate a double integral on a rectangular domain:

-->getf('DoubleIntegral.txt')

Calculation of the transformed double integral using function DoubleIntegral produces the
following values for different number of sub-intervals (20, 40, 80) in the grid that subdivides
the integration domain:
-->DoubleIntegral(-5,5,20,0,1,20,psi)
ans = 408.01234
-->DoubleIntegral(-5,5,40,0,1,40,psi)
ans = 418.2893
-->DoubleIntegral(-5,5,80,0,1,80,psi)
ans = 422.13844

Notice that we get a better approximation to the integral value by using a smaller number of
elements in the grid.
Next, we present the calculation of the double integral by dividing the integration region into
triangles and using function int2d.
Function ellipse is used to generate the triangles that define the elliptical domain R in order to
use SCILABs function int2d to calculate the double integral:
-->getf('ellipse')

A listing of function ellipse follows:


==================================================================================
function [X,Y] = ellipse(a,b,n)
//Calculates the coordinates of the triangles used to approximate an
//ellipse. The triangles have a vertex at the origin.
X = zeros(3,n)
Y = X
Dtheta = 2*%pi/n;
for j = 1:n
X(1,j) = 0.0
X(2,j) = a*cos((j-1)*Dtheta)
X(3,j) = a*cos(j*Dtheta)
Y(1,j) = 0.0
Y(2,j) = b*sin((j-1)*Dtheta)
Y(3,j) = b*sin(j*Dtheta)
end
X = clean(X)
Y = clean(Y)
p = ones(1,n)
plot2d(X,Y,p)

==================================================================================
Calculation of double integral using function int2d with 20, 40, 80, and 160 triangles produces
the following values.
-->[X,Y] = ellipse(5,3,20);[I,err]=int2d(X,Y,f)
err = 9.553E-14
I
= 387.56881
-->[X,Y] = ellipse(5,3,40);[I,err]=int2d(X,Y,f)
err = 9.164E-14
I
= 397.27081

-->[X,Y] = ellipse(5,3,80);[I,err]=int2d(X,Y,f)
err = 9.169E-14
I
= 399.73022
-->[X,Y] = ellipse(5,3,160);[I,err]=int2d(X,Y,f)
int2d: termination: function evaluations > MEVALS
err
I

= 9.781E-14
= 400.34721

The values err represent the error in the convergence of the integral, and not necessarily the
error between the actual integral and the numerical approximation.
Also, when using 160
triangles we get the same termination error found earlier. The following call to int2d avoids
the termination message:
-->[X,Y]=ellipse(3,5,160);[I,err]=int2d(X,Y,f,[1.e-10,1,200,20000,1])
err = 9.473E-14
I
= 400.3472

Notice that use of int2d produces a better approximation of the integral than using
DoubleIntegral, however, a large number of triangles is needed to obtain such approximation.
Recall that function DoubleIntegral uses a simple algorithm: the average of the four values of
the function f(x,y) in the sub-interval defined by x i < x < xi+1, yj < y < yj+1. Function int2d uses a
more sophisticated approximation to the integral.

Using SCILAB graphics library plotlib


SCILAB graphics library plotlib was created by Stephane Mottelet. A zip file containing the
librarys files can be downloaded from the authors website at:
http://www.dma.utc.fr/~mottelet/myplot.html

Instructions for installation in Windows operating systems


To install the plotlib library for SCILAB in a Windows operating system follow these steps:
1.

The file downloaded is plotlib-install.zip. Extract it to folder plotlib017b1-install.

2.

Within folder plotlib017b1-install, double click on the folder labeled windows .

3.

Do a right-click on the file install.bat and select the option Edit.

4.

Change the line that reads

@SET SCIDIR = "c:\Programs Files\Scilab2.5"

to read
@SET SCIDIR = "<your SCILAB directory>"

e.g., in my SCILAB installation I use:

@SET SCIDIR = "c:\Program Files\Scilab-2.6"

5.

Save the file install.bat (File > Save)

6.

Double click on file install.bat to perform the installation.

7. During installation SCILAB will be launched. Wait until SCILAB closes and press any key
to end installation.
After installation, the functions in plotlib will be loaded everytime you start SCILAB. Notice that
the SCILAB interface will now show the following lines:
Startup execution:
loading initial environment
loading plotlib v0.17b1
A help chapter on plotlib, entitled Matlab-like functions, will also be added to the SCILAB Help
Dialog. Use this facility to find out information on how to use the plotlib functions.

Contents of the plotlib graphics library


The plotlib library includes, among others, the following functions:

General functions
background clf delete fig foreground hold legend subplot title -

change background
clear a figure
deletes a window
creates/activates a figure.
change foreground
holds/releases current plot
adds a legend
create axes in tiled positions.
adds a title on top of a graph

Two-dimensional graph functions


plot :
semilogx :
semilogy :
loglog :
xlabel :
ylabel :
grid :

generic plot function.


plot with logarithmic x scale
plot with logarithmic y scale
plot with logarithmic x and y scale
adds a label on x axis
adds a label on y axis
add a grid on a two-dimensional graph

Three-dimensional functions
plot3 :
mesh :
surf :
surfl :
view :

plot lines and points in three-dimensional space.


three-dimensional mesh surface.
three-dimensional colored surface.
three-dimensional surface with lighting
sets the view point

Applications of these functions are presented next.


The function plot
Function plot can be used to produce a number of two-dimensional plots. Some examples are
shown next. It is recommended that you try the commands listed below in your SCILAB
program after installing library plotlib. To save space in this document, we do not show the
output graphics.
First, we generate a pair of data vectors:
-->x = [0:0.5:10]; y = sin(x)+2.5*sin(2*x)-1.2*sin(3*x);

A plot of the contents of vector y versus their indices (i.e., yk vs- k) can be obtained by using:
-->plot(y)

The resulting plot shows a series of straight segments joining the points (k,yK). This is the
default format produced by function plot. For example, to produce a plot of y-vs-x using the
default format you can try:
-->plot(x,y)

A third argument can be added to the call to function plot to modify the color of the line
produced. For color control, the third argument can be one of the follo wing characters:

y
c
g
w

produces
produces
produces
produces

a yellow line
a cyan color line
a green line
a white line

m
r
b
k

produces a
produces a
produces a
produces a

magenta color line


red line
blue line
black line

Try the following examples:


-->plot(x,y,'y')
-->plot(x,y,'g')

-->plot(x,y,'m')
-->plot(x,y,'b')

-->plot(x,y,'c')
-->plot(x,y,'w')

-->plot(x,y,'r')
-->plot(x,y,'k')

Notice that a white line on the default white background would be invisible.
option only when the graph background is other than white.

Use the w

The third option in the call to function plot can also be used to produce a discontinuous plot if
we use one of the following characters:
.
t
*
d
^

Uses
Uses
Uses
Uses
Uses

dots to plot points


treefoils to plot points
asterisks to plot points
blank diamonds for points
circle and cross for points

o
+
f
v

Uses
Uses
Uses
Uses

circles to plot data points


crosses to plot data points
filled diamonds for points
triangles for points

Try the following exercises:


-->plot(x,y,'.')
-->plot(x,y,'*')
-->plot(x,y,'^')

-->plot(x,y,'o')
-->plot(x,y,'f')

-->plot(x,y,'t')
-->plot(x,y,'d')

-->plot(x,y,'+')
-->plot(x,y,'v')

Three different types of lines can be plotted by using any of the following characters as the
third argument to function plot:
-

solid line

--

dashed line

-.

dashed-dot line

Try the following examples:


-->plot(x,y,'-')

-->plot(x,y,'--')

-->plot(x,y,'-.')

The thickness of the line produced by function plot can be changed by using as third argument
the characters 2, 3, ..., 9. The thickness of the resulting line will be 2, 3, ..., 9 times
larger than the original default thickness. Try the following examples:
-->plot(x,y,'2')
-->plot(x,y,'6')

-->plot(x,y,'3')
-->plot(x,y,'7')

-->plot(x,y,'4')
-->plot(x,y,'8')

-->plot(x,y,'5')
-->plot(x,y,'9')

The third argument in the call to function plot can be a combination of the possible characters
presented above. For example, to plot a broken line in magenta color use:
-->plot(x,y,'m--')

To plot a line including circles for the symbols and a dash-dot line, use:
-->plot(x,y,'o-.')

This plot will be produced using the default color (blue). If you rather have the results in
magenta color use:

-->plot(x,y,'mo-.')

Try the following combinations:


-->plot(x,y,'k+-')

-->plot(x,y,'c^')

-->plot(x,y,'rf-')

Line thickness can only be changed for the continuous line. Thus, the following calls to
function plot can change thickness and color of lines, but not its type.
-->plot(x,y,'r2')

-->plot(x,y,'r7')

-->plot(x,y,'m4')

-->plot(x,y,'c8')

The function hold


You may have noticed that every time that a new call to function plot is executed the current
plot gets replaced. By using function hold you can temporarily hold the current plot available
for adding a second data set or a different plot format. A second call to function hold will
actually release the current plot from holding. For example, the following set of calls will
produce a plot showing a continuous red line of triple thickness overlapping blue (default
value) crosses at the points plotted. SCILAB reports the current condition (held or released)
after each call to function hold:
-->plot(x,y,'r3')
-->hold()
Current plot held
-->plot(x,y,'+')
-->hold()
Current plot released

Other possible combinations for two different formats in the same plot are shown next:
-->plot(x,y,'mv');hold();plot(x,y,'c2');hold()
Current plot held
Current plot released
-->plot(x,y,'gf');hold();plot(x,y,'b3');hold()
Current plot held
Current plot released

Notice that in the following command line the b3 argument (blue, triple-thickness,
continuous line) in the first call to function plot will override the -. (dash-dot line) argument
of the second call to function plot:
-->plot(x,y,'gf-.');hold();plot(x,y,'b3');hold()
Current plot held
Current plot released

The combination of plot and hold can be used to plot two sets of data in the same set of axes.
To illustrate the use of these combinations we first generate the following vectors:
-->x = [0:0.5:10]; y = exp(-0.05*x).*cos(5*x); z = sin(x)+sin(2*x);

Next, we plot y-vs-x as a dashed line with magenta color, and z-vs-x as a number of red
crosses:
-->plot(x,y,'m--')
-->hold()
Current plot held
-->plot(x,z,'r+')
-->hold()

Because the range of z values is larger than the range of y values, plotting y-vs-x before z-vs-x
forces the z-vs-x data to go out of the main frame of the plot. In this case, it will be more
convenient to plot first z-vs-x as follows:
-->plot(x,z,'r+')
-->hold()
Current plot held
-->plot(x,y,'m--')
-->hold()
Current plot released

In the following example, three different functions are plotted in the same set of axes. First,
the data is generated and the minimum and maximum values of vectors x, y, and z, are
determined.
-->ymin=min(y),ymax=max(y),zmin=min(z),zmax=max(z),wmin=min(w),wmax=max(w)
ymin = - 4.0107702, ymax = 4.0104031,
zmin =
.0112096, zmax = .9999993
wmin = - .8636572, wmax =
.9577166

The largest range is provided by [x max ,xmin ]. Thus, we plot y-vs-x first, then we hold the current
graph, and add the plots of z-vs-x and w-vs-x. By plotting y-vs-x first we ensure that the range
of values of y will be large enough for all plots.
-->plot(x,y,'r-')
-->hold()
Current plot held
-->plot(x,z,'m+')
-->plot(x,w,'g2')

Adding grids and labels to a two-dimensional plot


To add a grid to your graph we can use the following call:
-->plot(x,y,'grid','on')

To remove the grid from the plot use:


-->plot(x,y,'grid','off')

To place a single-character label in x and y use functions xlabel and ylabel as follows:
-->xlabel('x'), ylabel('y')

A plot title can be added by using function title, for example:


-->title(motion graph)

You can place x labels with more of one character, for example,
-->plot(x,y)
-->xlabel('time(sec)')

However, trying to place a label in y that is longer than 1 character produces a messy y-label:
-->ylabel('displacement(mm)')

My recommendation is to use SCILABs own xtitle function. This function allows the user to
add a plot label as well as axes labels in x and y. The general call to function xtitle is:
xtitle(plot label,[x label, y label, box])

An example of function xtitle follows:


-->plot(x,y)
-->xtitle('movement of a particle','time(sec)','displacement(mm)')

Plots with logarithmic scales


Functions semilogx, semilogy, and loglog can be used to produce plots that have logarithmic
scales in the x-axis, in the y-axis, and in both axes, respectively. To illustrate their
applications try the following exercises. First, enter some data:
-->x = [0.5 14.5 153.6 789.5 1456.0 6789.0 11345.2 89567.3];
-->y = [12.5 13.6 17.8 25.3 38.7 12.56 8.32 2.34];

The plot using natural sca les is produced by using:


-->plot(x,y)

The following plot uses a logarithmic scale in the x-direction:


-->semilogx(x,y)

The following plot uses a logarithmic scale in the y-direction:


-->semilogy(y,x)

Finally, the following plot uses logarithmic scales in both the x- and y-directions:
-->loglog(x,y)

Functions semilogx, semilogy, and loglog can take a third argument similar to that used for
function plot as illustrated in the following examples:
-->loglog(x,y,'+')

-->semilogx(x,y,'r+-.')

-->semilogy(x,y,'r3')

-->loglog(x,y,'grid','on')

We can add labels to the plots produced with semilogx, semilogy, and loglog as illustrated
below:
-->loglog(x,y,'g3')
-->xtitle('pressure coefficient','Dp(kPa)','Cp')
-->semilogx(x,y,'r--')
-->xlabel('Dp'), ylabel('C')
-->title('pressure coefficient')

Plotting multiple graphs with a single plot call


You can plot several graphs in the same set of axes by using a call to the plot function of the
form plot(x,y1,x,y2,x,y3,). For example, using the values of x, y, z, and w, used in the
previous case, we can write:
-->plot(x,y,x,z,x,w)

Plot styles can also be included in the call to plot, for example,
-->plot(x,y,+,x,z,o,x,w,x)

Functions semilogx, semilogy, and loglog, can also be used to plot multiple data sets as
indicated in the following exercise:
-->x = [1,10,100,1000,10000]; y = sqrt(x);
-->z = x^(1/3); w = x^(1/4);
-->semilogx(x,y,x,z,x,w)
-->semilogy(y,x,z,x,w,x)
-->loglog(x,y,x,z,x,w)

Plot style specifications can also be added to the calls to functions semilogx, semilogy, and
loglog, as shown next:
-->semilogx(x,y,'r+',x,z,'b2',x,w,'f')

-->semilogy(y,x,'--',z,x,'-.',w,x,'-')
-->loglog(x,y,'+',x,z,'o',x,w,'x')

Adding legends to plots with multiple data sets


After a plot that includes multiple data sets is created, it is possible to add legends to
distinguish the different data sets. The legends are strings placed in the same order as the
data they represent. Using the data for x, y, z, and w, generated above, we produce the
following example that include legends in the plot:
-->semilogx(x,y,x,z,x,w)
-->legend('pressure 1','pressure 2', 'pressure 3')

The legends can be added to the plot command as illustrated next using the plot command
semilogx:
-->semilogx(x,y,x,z,x,w,'legend','temp 1','temp 2','temp 3')

It is possible to add an additional argument (a position argument), when including legends in a


plot, that lets you select the location of the legends. The possible values of the position
argument are:
-1
1
2
3
4
5

=
=
=
=
=
=

outside the axis box on the right


Upper right-hand corner (default)
Upper left-hand corner
Lower left-hand corner
Lower right-hand corner
Interactive placement with the mouse

The option position = -1 can only be used when the legend argument is included in a plot
command call. For example, try the following command:
-->plot(x,y,'r-',x,w,'g--','legend','sine','cosine',-1)

Other possible values of the position argument for legends are demonstrated with the following
calls:
-->plot(x,y,'+-.',x,w,'x-','legend','sine function','cosine function',1)
-->plot(x,y,'+-.',x,w,'x-','legend','sine function','cosine function',2)
-->plot(x,y,'+-.',x,w,'x-','legend','sine function','cosine function',3)
-->plot(x,y,'+-.',x,w,'x-','legend','sine function','cosine function',4)
-->plot(x,y,'+-.',x,w,'x-','legend','sine function','cosine function',5)

The latter command requires a mouse action by the user to select the location of the legend
box.
Creating, clearing, and deleting graphics windows
In all the examples presented above we have used a window entitled ScilabGraphic0. This is
the default graphics window provided by SCILAB (window 0).
Function fig can be used to
generate other graphics windows, for example, the call

-->fig(3)

generates window ScilabGraphic3 (graphics windows number three).


Subsequent plot
commands will modify the graph in this window. Try, for example, the following commands:
-->plot(x,y,--)

To clear the current graphics window use function clf (clear figure):
-->clf()

To delete a graphics window use function delete, for example,


-->delete(3)

Using the function fig with no arguments will produce a new graph with default attributes. The
numbe of the Scilab Graphics Window thus generated will be determined by the number of th e
last Scilab Graphics Window used. If no graphic windows are open, fig() will generate Scilab
Graphics Window 0. Try the following exercises:
-->x = [0:1:10]; y = sin(x)+cos(x);
-->fig();plot(x,y)
-->fig(5);plot(x,y)
-->clf(5);plot(y,x)
-->fig();plot(x,y)

Setting the background and foreground colors of a graph


The background of a graph corresponds to the area of the graphics window where the graph is
produced. The foreground represents the axes and labels of the graph. The colors of the
background and foreground can be changed by using the arguments background and
foreground in the call to function fig. When calling function fig, each of these arguments is
followed by a row vector of three elements [R G B] where the values R, G, and B are numbers
between 0 and 1 representing the levels of colors red (R), green (G), and blue (B), to be used.
The values R, G, and B, must add to one (i.e., R+G+B = 1). Some of the colors in the
background and foreground of a figure are represented by the following combination of 1s and
0s in the color vector:
[
[
[
[

0
0
1
1

0
1
0
1

0
0
0
0

]
]
]
]

black
green
red
yellow

[
[
[
[

0
0
1
1

0
1
0
1

1
1
1
1

]
]
]
]

blue
cyan
magenta
white

Other combinations of values, e.g., [ 0.33 0.33 0.34 ] or [ 0.50 0.25 0.25] will produce
intermediate colors.
To show some examples of background and foreground modification, first generate the
following data vectors:
-->x = [0:0.1:10]; y = sin(x);

A basic white background with black foreground is obtained by using, for example:

-->fig('background',[1 1 1],'foreground',[0 0 0]);plot(x,y)

The default color for the curve is blue. To change the curve's color to red, for example, we
can use the following option in the plot function:
-->plot(x,y,'r')

The followings are examples of other background and foreground combinations:


-->fig('background',[0 0 1],'foreground',[0 1 0]);plot(x,y)
-->fig('background',[0 0 1],'foreground',[0 1 0]);plot(x,y,'r')
-->fig('background',[0 0 1],'foreground',[0 1 0]);plot(x,y,'m2')
-->fig('background',[0.3 0.6 0.1],'foreground',[0 1 0]);plot(x,y,'m2')
-->fig('background',[0.3 0.6 0.1],'foreground',[0.2 0.8 0.0]);plot(x,y,'m2')
-->fig('background',[0.3 0.6 0.1],'foreground',[0.5 0.4 0.1]);plot(x,y,'m2')

To return to default colors for background and foreground use:


--> fig('background',[1 1 1],'foreground',[0 0 0]);

You can open any Scilab Graphic Window with your selected background and foreground colors
by including a window number in the call to function fig, for example,
-->fig(3,'background',[0 0 1],'foreground',[0 1 0]);plot(x,y,'m2')

Working with subplots


A graphics window can be divided into a number of sub-plots. For example, we can divide our
graphics window into four sub-plots placed in a graphics array of two rows and two columns.
To select a particular sub-plot in your graphics array, use function subplot. The following
commands let you produce four sub-plots in a single graphics window:
->subplot(2,2,1);plot(x,y,'r+-.');xtitle('plot(2,2,1)','x','y')
-->subplot(2,2,2);plot(x,z,'3');xtitle('plot(2,2,2)','x','y')
-->subplot(2,2,3);plot(x,w,'mv');xtitle('plot(2,2,3)','x','y')
-->subplot(2,2,4);plot(x,y,'-.');xtitle('plot(2,2,4)','x','y')

The general call to function subplot is subplot(nrows, ncols, plot#). The maximum value of
plot# is nrows ncols.
The following example uses 6 sub-plots:
-->subplot(2,3,1);plot(x,y1,'r+');xtitle('x','x','plot 1');
-->subplot(2,3,2);plot(x,y2,'gf');xtitle('x','x^2','plot 2');
-->subplot(2,3,3);plot(x,y3,'b6');xtitle('x','x^3','plot 3');
-->subplot(2,3,4);plot(x,y4,'cx');xtitle('x','x^5','plot 4');

10

-->subplot(2,3,5);plot(x,y5,'k5');xtitle('x','x^5','plot 5');
-->subplot(2,3,6);plot(x,y6,'-.');xtitle('x','x^6','plot 6');

The general call to function subplot is subplot(k,l,n), where k and l represent the number of
rows and columns in the graphical array.
If i represents the row and j represents the column in the graphical array where plot number n
will be placed. The relationship between i,j, and n, is given by
n = (j-1)k+i,
where k is the number of rows in the graphical array.
following schematic of the graphical array:

The location of plot n is shown in the

Basically, this graph and the relationship n=(j-1)k+i, indicate that the plots are filled by
columns, i.e., plot number 1 will show up in the upper left corner of the array, plot number 2
will be immediately below plot number 1, and so on until reaching plot number k. Plot number
k+1 will be in the top row, second column. Plot number k+2 will be located below plot number
k+1, and so on until k plots are positioned in column number 2. The process of plot positioning
will continue in this fashion until the total of lk plots are defined in the graphical array.
Plotting curves in three-dimensional space
Function plot3 produces the plots of curves in three-dimensional space. A single curve can be
produced by providing vectors x, y, and z, containing the coordinates of point on the curve.
For example, a curve defined by the following parametric equations:
-->deff('[x]=f1(t)','x=3.5*sin(t/2)')
-->deff('[y]=f2(t)','y=3.5*cos(t/2)')
-->deff('[z]=f3(t)','z=1.2*t')

can be described by the following vectors for 0 < t < 20:


-->t = [0:0.1:20]; x = f1(t); y = f2(t); z = f3(t);
-->plot3(x,y,z)

11

The resulting plot shows an helix curve in three dimensions represented by a continuous line.
Other symbols can be used to plot the individual points making up the curve by using the
specifications similar to those in function plot, for example:
-->plot3(x,y,z,+)

Several curves can be plotted using function plot3. For example, to generate several helices
with different radii we can use the following commands:
-->deff('[x]=f1(A,t)','x=A*sin(t)')

//Define x(t)

-->deff('[y]=f2(A,t)','y=A*cos(t)')

//Define y(t)

-->deff('[z]=f3(A,t)','z=A*t')

//Define z(t)

-->t=[0:0.1:40];

//Values of t

-->A=3;x1=f1(A,t);y1=f2(A,t);z1=f3(A,t);

//(x,y,z) data for A = 3

-->A=2;x2=f1(A,t);y2=f2(A,t);z2=f3(A,t);

//(x,y,z) data for A = 2

-->A=3;x3=f1(A,t);y3=f2(A,t);z3=f3(A,t);

//(x,y,z) data for A = 1

To plot the individual helices use:


-->plot3(x1,y1,z1)
-->plot3(x2,y2,z2)
-->plot3(x3,y3,z3)

The following commands shows plots of one,two, and three helices in the same set of axes,
each helix using different symbols for plotting the points:
-->plot3(x1,y1,z1,'+')
-->plot3(x1,y1,z1,'+',x2,y2,z2,'x')
-->plot3(x1,y1,z1,'+',x2,y2,z2,'x',x3,y3,z3,'-')

Several curves can be defined by matrices of values X, Y, Z, where the columns of each matrix
represent (x,y,z) data for each curve. To put together the matrices use:
-->X = [x1' x2' x3'];

//Put together X matrix

-->Y = [y1' y2' y3'];

//Put together Y matrix

-->Z = [z1' z2' z3'];

//Put together Z matrix

The call to function plot3 in this case is:


-->plot3(X,Y,Z)

//Plot the three helices

An additional argument can be used to modify the format of the curves, for example:
-->plot3(X,Y,Z,'r')
-->plot3(X,Y,Z,'-')
-->plot3(X,Y,Z,'--')

12

The format argument (e.g., r, -, etc.) applies equally to all curves defined by matrices X,
Y, and Z.
In a three-dimensional graph, the viewpoint is that imaginary point in space from which the
graph is observed. The viewpoint, for a three-dimensional graph generated with plot3, can be
changed by specifying two angles (in degrees) or the viewpoint coordinates in the function call.
These arguments, put together into a 2- o r 3-element vector, follow the argument view
which, in turn, follows the vectors of coordinates of the points in the curves. For example, to
generate the graph with a point of view at angles 20o and 50o, for the current X, Y, Z data use:
-->plot3(X,Y,Z,'-.','view',[20,50])

To produce the three-dimensional graph viewed from point (5,3,20) use:


-->plot3(X,Y,Z,'-.','view',[5,3,20])

Of course, once a three-dimensional plot has been generated by SCILAB, you can simply click
the menu option 3D Rot. in the Graphic Window, and drag the graph around to a different
viewpoint.
When producing a three-dimensional plot, function plot3d will generate a parallelpiped (i.e., a
rectangular box in space) large enough to contain the coordinates of the points in the curve,
or curves, plotted. You can change the dimensions of the parallelpiped by adding the
argument axis followed by a 6-element vector defining the extreme values of the x, y, and z
coordinates required, i.e., [xmin xmax ymin ymax zmin zmax]. For example, try the following
command:
-->plot3(X,Y,Z,'axis',[-5 5 -5 5 -10 200])

The following call to function plot3 redefines both the viewpoint and the coordinates
parallelpiped:
-->plot3(X,Y,Z,'-.','view',[1,1,20],'axis',[-5 5 -5 5 -10 200])

Plotting surfaces in three-dimensional space with function mesh


To generate data for a surface in three-dimensional space we need to provide vectors of x,y
values that define a rectangular grid in the x-y plane. For example:
-->x = [-5:0.5:5]; y = [-7.5:0.5:7.5]

We can use these vectors to produce a matrix of values zij = f(xi,yj) by defining a function
z=f(x,y) and, then, using function feval. For example:
-->deff('[z]=f(x,y)','z = x.*sin(y)+y.*sin(x)')
-->z = feval(x,y,f);

We can check that z is indeed a matrix by using function size:


-->size(z)
ans =
!

21.

31. !

To produce a mesh plot with the data in vectors x and y, and in matrix z, use:

13

-->mesh(x,y,z')

Notice that we use the transpose, z, of matrix z, in the call to function mesh.
We can also use the name of the function to be plotted (in this case, f) in the call to function
mesh, for example:
-->mesh(x,y,f)

A surface in three-dimensions can be generated by using parametric equations of the form


x=x(u,v), y=y(u,v), and z=z(u,v). For example, the following function defines the parametric
equations of a surface in three-dimensions:
-->deff('[x,y,z]=f(u,v)',['x=sin(u).*cos(v)','y=cos(u).*sin(v)','z=u+v'])

Given the following vectors of values of u and v,


-->u = [0:0.1:1]; v = [1:0.1:2];

to generate the corresponding three-dimensional surface use:


-->mesh(u,v,f)

It is possible to eliminate the axes from the plot by using the options axis,off in the call
to function mesh. For example:
-->x = [-5:0.5:5]; y = [-7.5:0.5:7.5]
-->deff('[z]=f(x,y)','z = x.*sin(y)+y.*sin(x)');z = feval(x,y,f);
-->mesh(x,y,z','axis','off')

It is also possible to alter the colors of the faces and edges of the three-dimensional mesh by
using the arguments facecolor and edgecolor followed by [R G B] vectors as illustrated
next:
-->mesh(x,y,z','axis','off','facecolor',[1 0 0],'edgecolor',[0 0 1])

Plotting three-dimensional surfaces with function surf


If you want to generate a solid surface use function surf. The general call to function surf is
very similar to that of function mesh. Some examples are shown below:
In this example, we define a function z = f(x,y):
-->deff('[z]=f(x,y)','z = x.*sin(y)+y.*sin(x)')

Next, generate vectors of values of x and y, and evaluate the function f(x,y) into matrix z:
-->x = [-5:0.5:5]; y = [-7.5:0.5:7.5];
-->z = feval(x,y,f);

To plot the solid surface z = f(x,y), use the following call to function surf:

14

-->surf(x,y,z')

Alternatively, given the function f(x,y), you can use the following call to function surf:
-->surf(x,y,f)

For parametric equations, we can use, for example:


-->deff('[x,y,z]=f(u,v)',['x=sin(u).*cos(v)','y=cos(u).*sin(v)','z=u+v'])
-->u = [0:0.1:1]; v = [1:0.1:2];
-->surf(u,v,f)

As in function mesh, with function surf you can eliminate the axes and change the colors of the
faces and edges of the surface mesh. Try the following examples:
-->surf(x,y,z')
-->surf(x,y,z','axis','off')
-->surf(x,y,z','axis','off','edgecolor',[0 0 1],'facecolor',[1 1 0])

The following call to function surf eliminates the axes and produces a smooth surface coloring:
-->surf(x,y,z,'axis','off','shading','flat')

Function surf admits a fourth argument, a vector or function g(x,y), can be used to generate
the coloring of the surface face components. Try the following examples:
-->deff('[z]=f(x,y)','z=x.*sin(y)+y.*sin(x)')
-->deff('[c]=g(x,y)','c=x^2+y^2')
-->x = [-5:0.5:5]; y = [-7.5:0.5:7.5];
-->z = feval(x,y,f); c = feval(x,y,g);
-->surf(x,y,z',c')

Alternatively, you can use the following function call:


-->surf(x,y,f,g)

Three dimensional plots with function surfl


Function surfl produces surface plots similar to those produced by surf but with light and
shadow effects on the surface. Some examples are shown below:
-->deff('[z]=f(x,y)','z = x.*sin(y)+y.*sin(x)')
-->x = [-5:0.5:5]; y = [-7.5:0.5:7.5];
-->z = feval(x,y,f);
-->surfl(x,y,z')

Alternatively, given the function f(x,y), you can use the following call to function surf:

15

-->surfl(x,y,f)

For parametric equations, we can use, for example:


-->deff('[x,y,z]=f(u,v)',['x=sin(u).*cos(v)','y=cos(u).*sin(v)','z=u+v'])
-->u = [0:0.1:1]; v = [1:0.1:2];
-->surfl(u,v,f)

As in functions mesh and surf, with function surfl you can eliminate the axes and change the
colors of the faces and edges of the surface mesh. Try the following examples:
-->surfl(x,y,z')
-->surfl(x,y,z','axis','off')
-->surfl(x,y,z','axis','off','edgecolor',[0 0 1],'facecolor',[1 1 0])

Like function surf, function surfl admits a fourth argument, a vector, that can be used to
generate the coloring of the surface face components. Try the following examples:
-->deff('[z]=f(x,y)','z=x.*sin(y)+y.*sin(x)')
-->deff('[c]=g(x,y)','c=x^2+y^2')
-->x = [-5:0.5:5]; y = [-7.5:0.5:7.5];
-->z = feval(x,y,f); c = feval(x,y,g);
-->surfl(x,y,z',c')

==================================================================================
This document was prepared by Gilberto E. Urroz, Ph.D., P.E., Associate Professor, Department
of Civil and Environmental Engineering, Utah State University. November 2, 2001.
==================================================================================

16

Catalog references for input and output in SCILAB


This file describe some of the output and input functions for SCILAB. The information was
obtained from the SCILAB help facility.

Commands for printing include


o

C-like commands
! printf: prints to screen
! fprintf: prints to a file
! sprintf: prints to a string variable
! fprintfMat: prints a matrix to a file

FORTRAN-like output to a file


! write: formatted writing to a file or to screen

SCILAB owns command


! disp: prints to screen (display)

Commands for reading (scanning) include

o C-like commands
! scanf: input from the screen
! fscanf: input from a file
! sscanf: input from a string
o FORTRAN-like commands
! read: reads data from file or screen
o SCILAB owns command
! input: reads data from screen
C-like commands for printing in SCILAB
printf(format,value_1,..,value_n)
fprintf(file,format,value_1,..,value_n)
str=sprintf(format,value_1,..,value_n)
fprintfMat(file,M,format)
mfprintf(fd,format,value_1,..,value_n);
mprintf(format,value_1,..,value_n);
str=msprintf(format,value_1,..,value_n);
where
format = conversion specifications for output
value_1, value_2, , value_n = values to be output in the conversion specifications
file = file specification for fprintf and mfprintf
str = a string variable
M = a matrix of real numbers

printf, sprintf, fprintf conversion specifications


DESCRIPTION
Each conversion specification in the printf , sprintf , fprintf format parameter has the
following syntax:
-

A % (percent) sign.

- Zero or more options, which modify the meaning of the conversion specification. The
following list contains the option characters and their meanings:
-

: Left align, within the field, the result of the conversion.

: Begin the result of a signed conversion with a sign (+ or -).

"space" : Prefix a space character to the result if the first character of a signed conversion
is not a sign. If both the (space) and + options appear, the (space) option is ignored.
#
: Convert the value to an alternate form. For c, d, i, s, and u conversions, the #
option has no effect. For o conversion, # increases the precision to force the first digit of the
result to be a 0 (zero). For x and X conversions, a nonzero result has 0x or 0X prefixed to it.
For e, E, f, g, and G conversions, the result always contains a decimal point, even if no digits
follow it. For g and G conversions, trailing zeros are not removed from the result.
0
: Pad to the field width, using leading zeros (following any indication of sign or base)
for d, i, o, u, x, X, e, E, f, g, and G conversions, no space padding is performed. If the 0 and \(dash) flags both appear, the 0 flag is ignored. For d, i, o, u, x, and X conversions, if a
precision is specified, the 0 flag is also ignored.
An optional decimal digit string that specifies the minimum field width. If the converted
value has fewer characters than the field width, the field is padded on the left to the length
specified by the field width. If the left-adjustment option is specified, the field is padded on
the right.
An optional precision. The precision is a . (dot) followed by a decimal digit string. If no
precision is given, the parameter is treated as 0 (zero). The precision specifies:

The minimum number of digits to appear for d, u, o, x, or X conversions

The number of digits to appear after the decimal point for e, E, and f conversions

The maximum number of significant digits for g and G conversions

The maximum number of characters to be printed from a string in an s conversion

A character that indicates the type of conversion to be applied:


%

: Performs no conversion. Displays %.

d,i :Accepts an integer value and converts it to signed decimal notation. The precision
specifies the minimum number of digits to appear. If the value being converted can be
represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The
result of converting a zero value with a precision of zero is a null string. Specifying a field
width with a zero as a leading character causes the field width value to be padded with leading
zeros.

u
:Accepts an integer value and converts it to unsigned decimal notation. The precision
specifies the minimum number of digits to appear. If the value being converted can be
represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The
result of converting a zero value with a precision of zero is a null string. Specifying a field
width with a zero as the leading character causes the field width value to be padded with
leading zeros.
o
:Accepts an integer value and converts it to unsigned octal notation. The precision
specifies the minimum number of digits to appear. If the value being converted can be
represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The
result of converting a zero value with a precision of zero is a null string. Specifying a field
width with a zero as the leading character causes the field width value to be padded with
leading zeros. An octal value for field width is not implied.
x, X :Accepts an integer value and converts it to unsigned hexadecimal notation. The
letters '''abcdef'' are used for the x conversion; the letters ''ABCDEF'' are used for the X
conversion. The precision specifies the minimum number of digits to appear. If the value being
converted can be represented in fewer digits, it is expanded with leading zeros. The default
precision is 1. The result of converting a zero value with a precision of zero is a null string.
Specifying a field width with a zero as the leading character causes the field width value to be
padded with leading zeros.
f
: Accepts a float or double value and converts it to decimal notation in the format %[\]ddd.ddd. The number of digits after the decimal point is equal to the precision specification.
-

If no precision is specified, six digits are output.

- If the precision is zero, no decimal point appears and the system outputs a number
rounded to the integer nearest to value.
-

If a decimal point is output, at least one digit is output before it.

e, E :Accepts a real and converts it to the exponential form %[\-]d.ddde+/\-dd. There is


one digit before the decimal point, and the number of digits after the decimal point is equal to
the precision specification.
-

If no precision is specified, six digits are output.

If the precision is zero, , no decimal point appears.

The E conversion character produces a number with E instead of e


before the exponent. The exponent always contains at least two
digits. If the value is zero, the exponent is zero.

g, G : Accepts a real and converts it in the style of the e, E, or f conversion characters,


with the precision specifying the number of significant digits. Trailing zeros are removed from
the result. A decimal point appears only if it is followed by a digit. The style used depends on
the value converted. Style e (E, if G is the flag used) results only if the exponent resulting from
the conversion is less than -4, or if it is greater or equal to the precision.
c

:Accepts and displays an integer value converted to a character.

s
:Accepts a string value and displays characters from the string to the end or the
number of characters indicated by the precision is reached. If no precision is specified, all
characters up to the end are displayed.
A field width or precision can be indicated by an * (asterisk) instead of a digit string. In this
case, an integer value parameter supplies the field width or precision. The value parameter
converted for output is not fetched until the conversion letter is reached, so the parameters
specifying field width or precision must appear before the value to be converted (if any). If
the result of a conversion is wider than the field width, the field is expanded to contain the
converted result. The representation of the plus sign depends on whether the + or (space)
formatting option is specified.
C-like commands for reading in SCILAB
[value_1, value_2, , value_n]=scanf (format);
[value_1, value_2, , value_n]=fscanf (file,format)
[value_1, value_2, , value_n]=sscanf (string,format)
M = fscanfMat(file);
where
format = conversion specifications for output
value_1, value_2, , value_n = values to be output in the conversion specifications
file = file specification for fprintf and mfprintf
string = a string containing the values to be converted
scanf, sscanf, fscanf conversion specifications
Each conversion specification in the format parameter contains the following elements:
+

The character % (percent sign)

The optional assignment suppression character *

An optional numeric maximum field width

A conversion code
The conversion specification has the following syntax:
[*][width][size]convcode.

The results from the conversion are placed in value_i arguments unless you specify
assignment suppression with * (asterisk). Assignment suppression provides a way to describe an
input field that is to be skipped. The input field is a string of nonwhite-space characters. It
extends to the next inappropriate character or until the field width, if specified, is exhausted.
The conversion code indicates how to interpret the input field. You should not specify the
value_i parameter for a suppressed field. You can use the following conversion codes:
%

:Accepts a single % (percent sign) input at this point; no assignment is done.

d, i :Accepts a decimal integer;

:Accepts an unsigned decimal integer;

:Accepts an octal integer;

:Accepts a hexadecimal integer;

e,f,g: Accepts a floating-point number. The next field is converted accordingly and stored
through the corresponding parameter, which should be a pointer to a float. The input format
for floating-point numbers is a string of digits, with the following optional characteristics:
+

It can be a signed value.

It can be an exponential value, containing a decimal point


followed by an exponent field, which consists of an E or an e
followed by an (optionally signed) integer.

It can be one of the special values INF, NaN,

s:

Accepts a string of characters.

c:

character value is expected. The normal skip over white space is suppressed.

FORTRAN-like output to a file


write(file,a,[format])
write(file,a,k,format)
where
file-desc : character string specifying the file name or integer value
specifying logical unit (see file).
a

: real matrix or column vector of character strings.

format
: character string, specifies a "Fortran" format. This character string must begin with
a right parenthesis and end with a left parenthesis. Formats cannot mix floating point, integer
or character edition modes.
k
: integer vector
For direct access files: x=write(file,a,k,format). Here k is the vector of records (one record by
row, i.e. m=prod(size(k))
FORTRAN-like matrix input from a file
[x]=read(file,m,n,[format])
[x]=read(file,m,n,k,format)
where
file: character string specifying the file name or integer value specifying logical unit (see file).

m, n: integers (dimensions of the matrix x). Set m=-1 if you do not know the numbers of rows,
so the whole file is read.
format : character string, specifies a "Fortran" format. This character string must begin with a
right parenthesis and end with a left parenthesis. Formats cannot mix floating point or
character edition modes.
k

: integer or vector of integer

When format is omitted data are read using numerical free format. Blank, comma, and slash
may be used as data separators, n*v may be use to represent n occurrences of value v.
A direct access file can be used if using the parameter k which is the vector of record numbers
to be read (one record per row), thus m must be m=prod(size(k)).
Some FORTRAN format specifications
Iw:
Fw.d:
Ew.d:
w>d+7
Aw:

Integer output field of width w


Floating point output field of width w with d decimal places, with at least w>d+3
Floating point using scientific notation, of width w and d decimal places, with at least
Alphanumeric (string) output field of width w

SCILAB own output functions


disp(x1,[x2,...xn])
Displays xi to the screen with the current format. xi's are arbitrary objects (matrices of
constants, strings, functions, lists, ...)
print('file-name',x1,[x2,...xn])
Prints xi on file 'file-name' with the current format, i.e. the format used by SCILAB to display
the variables.
SCILAB own input functions
[x]=input(message,["string"])
where
message

character string

"string" :

the character string "string" (may be abbreviated to "s")

real number (or character string if "string" is in the calling sequence)

Examples of SCILAB functions that emulate Matlab functions


The functions are presented in alphabetical order:
mtlb
mtlb_cell
mtlb_diff
mtlb_eye
mtlb_findstr
mtlb_fread
mtlb_hold
mtlb_ishold
mtlb_loglog
mtlb_mesh
mtlb_plot
mtlb_save
mtlb_sscanf

mtlb_all
mtlb_choices
mtlb_e
mtlb_fft
mtlb_fliplr
mtlb_fscanf
mtlb_i
mtlb_isreal
mtlb_max
mtlb_meshdom
mtlb_prod
mtlb_semilogx
mtlb_subplot

mtlb_any
mtlb_clf
mtlb_eval
mtlb_filter
mtlb_flipud
mtlb_fwrite
mtlb_ifft
mtlb_length
mtlb_mean
mtlb_min
mtlb_qz
mtlb_semilogy
mtlb_sum

mtlb_axes
mtlb_cumsum
mtlb_exist
mtlb_find
mtlb_fprintf
mtlb_get
mtlb_is
mtlb_load
mtlb_median
mtlb_ones
mtlb_rand
mtlb_sprintf
mtlb_zeros

Examples are shown next.


mtlb
Converts matrices or functions to Matlab format. Used particularly to check functions before evaluating
them. The listing of the function is:

function x=mtlb(a)
if type(a)==13|type(a)==11 then
x=a()
else
x=a
end
Note type = 11 is an uncompiled function, while type = 13 is a compiled function.
mtlb_all
Use this function to determine if all elements of each column in a matrix are non-zero. If any term in a
column is zero, the result for that column is F (false). Example:

-->A = [3,0,1; 8 4 5]
A =
!
!

3.
8.

0.
4.

1. !
5. !

-->mtlb_all(A)
ans =
! T F T !
mtlb_any
Use this function to determine if any of the elements of each column of a matrix is non-zero. If at least one
of the elements in the column is not zero, the result for that column is T (true). Example:

-->A = [3,0,1; 8 4 5]

A
!
!

=
3.
8.

0.
4.

1. !
5. !

-->mtlb_any(A)
ans =
! T T T !
mtlb_axes
This function is no longer available in SCILAB version 2.6.
mtlb_cell
This function creates an array of empty matrices. For example,

-->Mcell = mtlb_cell(3,2)
Mcell =
Mcell(1)
cell
Mcell(2)
!

3.

2. !
Mcell(3)

[]
[More (y or n ) ?]
Mcell(4)
[]
Mcell(5)
[]
Mcell(6)
[]
Mcell(7)
[]
[More (y or n ) ?]
Mcell(8)
[]
In this example the variable Mcell is a SCILAB typed list with 8 elements. The first element Mcell(1)
identifies the list as a cell. The second element Mcell(2) stores the dimensions of the cell array. The
remaining 6 elements are the empty matrices composing the cell array.

mtlb_choices
Similar to SCILAB functions xchoose. Use xchoose in your applications.
mtlb_clf
Clears the contents of the current graphics window. As an example, produce the following graph:
-->x = [0:0.1:10]; y = sin(x) + sin(2*x);
-->plot(x,y,'x','y','plot example')
Then, watch as the graphics windows is cleared by using:
-->mtlb_clf
mtlb_cumsum
The function mtlb_cumsum produces a matrix whose element i,jrepresents the cumulative sum of the
elements in column j up to element i,j, e.g.,
-->A = int(10*rand(6,3))
A =
!
!
!
!
!
!

2.
7.
0.
3.
6.
6.

8.
6.
8.
0.
5.
6.

7.
1.
5.
2.
2.
2.

!
!
!
!
!
!

-->mtlb_cumsum(A)
ans =
!
!
!
!
!
!

2.
9.
9.
12.
18.
24.

8.
14.
22.
22.
27.
33.

7.
8.
13.
15.
17.
19.

!
!
!
!
!
!

In contrast, SCILAB's cumsum function produces a matrix whose element i,j is the cumulative sum of all
elements in columns 1 to i and up to element i,j in column j, i.e.,
-->cumsum(A)
ans =
!
!
!
!
!
!

2.
9.
9.
12.
18.
24.

32.
38.
46.
46.
51.
57.

64.
65.
70.
72.
74.
76.

!
!
!
!
!
!

mtlb_diff
This function can be used, for example, to calculate the differences between consecutive elements in a
vector. The following application uses a vector u with 7 elements:
-->u = [0, 1, 3, 6, 11, 15, 23]
u =
!

0.

1.

3.

6.

11.

15.

23. !

function mtlb-_diff produces a vector of 6 elements representing the differences between consecutive
elements of the original vector:
-->Du = mtlb_diff(u)
Du =
!

1.

2.

3.

5.

4.

8. !

Consecutive applications of the function mtlb-_diff produce vectors of differences with one less element
than the previous vector:
-->D2u = mtlb_diff(Du)
D2u =
!

1.

1.

2.

- 1.

4. !

-->D3u = mtlb_diff(D2u)
D3u =
!

0.

1.

- 3.

5. !

-->D4u = mtlb_diff(D3u)
D4u =
!

1.

- 4.

8. !

-->D5u = mtlb_diff(D4u)
D5u =
! - 5.

12. !

-->D6u = mtlb_diff(D5u)
D6u =
17.
The following example shows the application of function mtlb_diff to a column vector v of six elements,
and consecutive applications to the resulting vector until a single value is obtained:

-->v = [1;3;5;9;12;23]
v =
!
1. !
!
3. !
!
5. !
!
9. !
!
12. !
!
23. !
-->Dv =
Dv =
!
2.
!
2.
!
4.
!
3.
!
11.

mtlb_diff(v)
!
!
!
!
!

-->D2v = mtlb_diff(Dv)
D2v =
!
0. !
!
2. !
! - 1. !
!
8. !
-->D3v = mtlb_diff(D2v)
D3v =
!
2. !
! - 3. !
!
9. !
-->D4v = mtlb_diff(D3v)
D4v =
! - 5. !
!
12. !
-->D5v = mtlb_diff(D4v)
D5v =
17.
The following example shows the application of function mtlb_diff to a 5 4 matrix. The result of mtlb_diff,
when applied to matrices, is another matrix containing the differences between consecutive rows of the
original matrix:

-->A = int(10*rand(5,4))
A =
!
2.
9.
5.
4. !
!
2.
2.
4.
2. !
!
8.
3.
3.
6. !
!
6.
3.
5.
4. !
!
3.
2.
5.
9. !

-->DA = mtlb_diff(A)
DA =
!
0. - 7. - 1. !
6.
1. - 1.
! - 2.
0.
2. ! - 3. - 1.
0.

2.
4.
2.
5.

!
!
!
!

Continuous application of function mtlb_diff to the resulting matrix continues until the matrix is reduced to
a row vector:
-->D2A = mtlb_diff(DA)
D2A =
!
6.
8.
0.
6. !
! - 8. - 1.
3. - 6. !
! - 1. - 1. - 2.
7. !
-->D3A = mtlb_diff(D2A)
D3A =
! - 14.
!
7.

- 9.
0.

3.
- 5.

- 12. !
13. !

-->D4A = mtlb_diff(D3A)
D4A =
!

21.

9.

- 8.

25. !

From this point on, further applications of mtlb_diff will produce row vectors of smaller sizes until a single
value results:
-->D5A = mtlb_diff(D4A)
D5A =
! - 12. - 17.
33. !
-->D6A = mtlb_diff(D5A)
D6A =
! - 5.
50. !
-->D7A = mtlb_diff(D6A)
D7A =
55.

mtlb_e
Function mtlb_e with arguments A, k, i.e., mtlb_e(A,k) extracts element i,j from matrix A, of dimensions
mn, such that k = mi + j. In other words, mtlb_e(A,k) extracts the k-th element of the vector obtained by
placing each column of A one after the other. As an example, try the following commands:
-->A = int(10*rand(6,3))

A
!
!
!
!
!
!

=
2.
7.
0.
3.
6.
6.

8.
6.
8.
0.
5.
6.

7.
1.
5.
2.
2.
2.

!
!
!
!
!
!

-->mtlb_e(A,3)
ans =
0.
-->mtlb_e(A,2)
ans =
7.
-->mtlb_e(A,1)
ans =
2.
-->mtlb_e(A,11)
ans =
5.
The function is also intended to extract characters out of a string, for example:
--> a = tres tristes tigres
--> mtlb_e(a,[1:3])
ans

tre

mtlb_eval
Evaluates the string used as argument of the function as a SCILAB command. For example:

-->x1 = [0:0.5:10]; y1 = sin(x1);


-->mtlb_eval('mtlb_plot(x1,y1)')
!
!
!
!
!mtlb_plot(mtlb(x1),mtlb(y1));
ans =

!
!
!
!
!

[]
It is recommended that you use the SCILAB function execstr instead of mtlb_eval.

mtlb_exist
Checks if a variable exists in the active SCILAB memory. If it exists, a 1 is returned. Otherwise, the
function returns a zero. For example,

-->x1 = [0:0.1:1];
-->mtlb_exist('x1')
ans =
1.
-->mtlb_exist('x6')
ans =
0.
mtlb_eye
Used this function to produce a square identity matrix, giving a single argument representing the matrix
dimension in one direction, e.g.,
-->mtlb_eye(3)
ans =
!
!
!

1.
0.
0.

0.
1.
0.

0. !
0. !
1. !

Using SCILAB's eye function, the corresponding call is:


-->eye(3,3)
ans
!
!
!

1.
0.
0.

0.
1.
0.

0. !
0. !
1. !

mtlb_fft
When applied to a matrix, this function produces the one-dimensional Fast Fourier Transform of each
column of the matrix. In contrast, SCILAB fft transform produces the two-dimensional Fast Fourier
Transform of the two-dimensional signal represented by the matrix. Try the following exercise:
-->A = int(10*rand(10,4))
A =
!
!
!
!
!
!

3.
7.
6.
7.
7.
5.

9.
7.
1.
5.
3.
4.

5.
6.
0.
9.
1.
2.

7.
7.
4.
0.
0.
5.

!
!
!
!
!
!

!
!
!
!

9.
9.
3.
3.

3.
6.
2.
4.

1.
8.
4.
6.

0.
3.
3.
4.

!
!
!
!

-->mtlb_fft(A)
ans =

column 1 to 2
!
!
!
!
!
!
!
!
!
!

59.
- 9.0172209 - 2.126627i
- 4.190983 - 8.6452654i
5.5172209 - 1.3143278i
- 5.309017 + 1.2285711i
- 3. - 1.110E-16i
- 5.309017 - 1.2285711i
5.5172209 + 1.3143278i
- 4.190983 + 8.6452654i
- 9.0172209 + 2.126627i

44.
6.572949 + .1387573i
6.927051 - 2.8531695i
9.927051 - 4.0287401i
3.572949 - 1.7633558i
- 8. - 4.441E-16i
3.572949 + 1.7633558i
9.927051 + 4.0287401i
6.927051 + 2.8531695i
6.572949 - .1387573i

!
!
!
!
!
!
!
!
!
!

column 3 to 4
!
42.
!
7.072949 + 2.8531695i
! - 5.663119 + 2.9389263i
!
10.427051 - 1.7633558i
!
2.163119 - 4.7552826i
! - 20. + 3.331E-16i
!
2.163119 + 4.7552826i
!
10.427051 + 1.7633558i
! - 5.663119 - 2.9389263i
!
7.072949 - 2.8531695i

33.
12.135255 + .1387573i
7.309017 - 5.2043106i
- 4.6352549 - 4.0287401i
6.190983 + 2.0408703i
- 5. - 4.441E-16i
6.190983 - 2.0408703i
- 4.6352549 + 4.0287401i
7.309017 + 5.2043106i
12.135255 - .1387573i

!
!
!
!
!
!
!
!
!
!

17. - 11.i
- 16.09017 + .5825093i
3.823277 - 11.202226i
- 4.9098301 - 14.113278i
- 11.276362 + 8.6018876i
17. + 3.i
- 3.6679099 - 3.3658197i
- 4.9098301 - 15.011334i
- .8790051 + 11.966158i
- 16.09017 + 10.542102i

!
!
!
!
!
!
!
!
!
!

-->fft(A,-1)
ans =

column 1 to 2
!
178.
!
16.763932 + 1.0040571i
!
4.381966 - 13.763819i
!
21.236068 - 11.135164i
!
6.618034 - 3.249197i
! - 36. - 6.661E-16i
!
6.618034 + 3.249197i
!
21.236068 + 11.135164i
!
4.381966 + 13.763819i
!
16.763932 - 1.0040571i
column 3 to 4

!
!
!
!
!
!
!
!
!
!

24.
- 20.652476 + .4490280i
- 24.09017 + 2.351141i
10.652476 + 4.9797966i
- 12.90983 - 3.8042261i
- 10. + 1.110E-15i
- 12.90983 + 3.8042261i
10.652476 - 4.9797966i
- 24.09017 - 2.351141i
- 20.652476 - .4490280i

17. + 11.i
- 16.09017 - 10.542102i
- .8790051 - 11.966158i
- 4.9098301 + 15.011334i
- 3.6679099 + 3.3658197i
17. - 3.i
- 11.276362 - 8.6018876i
- 4.9098301 + 14.113278i
3.823277 + 11.202226i
- 16.09017 - .5825093i

!
!
!
!
!
!
!
!
!

mtlb_filter
This function is related to filtering of signals in linear systems. For more details, refer to the on-line Matlab
documentation at: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.shtml

mtlb_find
Similar to SCILAB's function find. Use help find to learn more about this function. I recommend you use
SCILAB function find rather than mtlb_find.
mtlb_findstr
Similar to function strindex in SCILAB. For example, the following two commands produce the same
result:
-->mtlb_findstr('mi','miami')

ans
!

=
1.

4. !

-->strindex('miami','mi')
ans =
!

1.

4. !

Notice the order of the strings in the function calls. The result from both function calls is to identify the
location in the string 'miami' where the sub-string 'mi' starts.
mtlb_fliplr
This function flips a matrix from left to right. As an example, try the following commands:
-->A = int(10*rand(3,6))
A =
!
!
!

6.
6.
0.

5.
7.
4.

4.
0.
0.

0.
3.
6.

1.
2.
4.

4. !
5. !
5. !

-->mtlb_fliplr(A)
10

ans
!
!
!

4.
5.
5.

1.
2.
4.

0.
3.
6.

4.
0.
0.

5.
7.
4.

6. !
6. !
0. !

mtlb_flipud
This function flips a matrix upside-down. As an example, try the following commands:
-->B = int(10*rand(6,3))
B =
!
!
!
!
!
!

0.
5.
0.
6.
0.
7.

6.
6.
9.
1.
7.
0.

8.
0.
6.
7.
2.
9.

!
!
!
!
!
!

-->mtlb_flipud(B)
ans =
!
!
!
!
!
!

7.
0.
6.
0.
5.
0.

0.
7.
1.
9.
6.
6.

9.
2.
7.
6.
0.
8.

!
!
!
!
!
!

mtlb_fprintf, mtlb_fread, mtlb_fscanf, mtlb_fwrite, mtlb_sprintf, mtlb_sscanf


These functions are used for input and output of data to files or the screen. Similarly-named functions exist
in SCILAB. Use the help facility in SCILAB to get more information.
mtlb_get
Similar to SCILAB function get. See the help file for get for more details on the use of the get function.
mtlb_hold
When using the command mtlb_plot, you can use mtlb_hold() to plot more than one graph in the same set
of axes. For example, the following commands produce the graph shown below:
-->x = [0:0.1:10]; y = sin(x); z = cos(x)+sin(x);
-->mtlb_plot(x,z,'+')
ans =
[]
-->mtlb_hold()

11

-->x = [0:0.1:10]; y = sin(x); z = cos(x)+sin(x);


-->mtlb_plot(x,z,'+')
ans =
[]
-->mtlb_hold()
-->mtlb_plot(x,y,'-')
ans =
[]
-->mtlb_hold()

The second use of function mtlb_hold() is used to release the current graph window for plotting. Thus, if a
new mtlb_plot, or even a SCILAB plot, command is used, a new graph will be created that will overwrite
the existing graph in the active graphics window.
mtlb_i
This function is used to insert an element b into a matrix A, of dimensions mn, so that the element location
i,j is given by the number k = im + j. The function call is mtlb_i(A,k,b). As an example try the following
commands:
-->A = mtlb_zeros(4)
A =
!
0.
0.
0.
!
0.
0.
0.
!
0.
0.
0.
!
0.
0.
0.

0.
0.
0.
0.

!
!
!
!

-->mtlb_i(A,10,-2)
ans =
!
0.
0.
0.
!
0.
0. - 2.
!
0.
0.
0.
!
0.
0.
0.

0.
0.
0.
0.

!
!
!
!
12

-->A=mtlb_i(A,6,3)
A =
!
!
!
!

0.
0.
0.
0.

0.
3.
0.
0.

0.
0.
0.
0.

0.
0.
0.
0.

!
!
!
!

0.
0.
0.
0.

!
!
!
!

-->mtlb_i(A,10,-2)
ans =
!
!
!
!

0.
0.
0.
0.

0.
3.
0.
0.

0.
- 2.
0.
0.

mtlb_ifft
This function can be used to calculate the one-dimensional Inverse Fast Fourier Transform of each of the
columns of a matrix. For example, given a matrix w:
-->w = int(10*rand(10,3)) + %i*int(10*rand(10,3))
w =
!
!
!
!
!
!
!
!
!
!

2.
5.
5.
1.
2.
6.
7.
i
6.
2.

+
+
+
+
+

8.i
9.i
5.i
5.i
8.i

+ 5.i
+ 7.i
+ 2.i

3.
8.
5.
4.
2.
8.
1.
2.
8.
8.

+ 5.i
+ 9.i
+ 7.i
+
+
+
+
+
+

5.i
3.i
2.i
6.i
i
6.i

5. +
9. +
6.
9. +
3.i
7. +
4. +
6. +
8. +
0

6.i !
3.i !
!
5.i !
!
2.i !
5.i !
4.i !
2.i !
!

Its inverse FFT is:


-->s = mtlb_ifft(w)
s =

column 1 to 2
!
!
!
!
!
!
!
!
!
!

3.6 + 5.i
- 1.030783 + .7060497i
.2958553 + .7286984i
- 1.9807131 + .1861819i
- .9293548 + .0750293i
.8 + 1.6i
.6821412 - 1.2458497i
- .3137141 + .5666045i
.3513583 - .5578780i
.5252102 + .9411638i

4.9 + 4.4i
.4153628 +
.5553423 2.0386679 1.2912678 1.1 - .4i
.9912678 .8974001 .8553423 +
1.1207051 +

13

.8726899i
.0417847i
.0551328i
.1304639i
.9639633i
.3629012i
.7362119i
.9453441i

!
!
!
!
!
!
!
!
!
!

column 3
!
!
!
!
!
!
!
!
!
!

5.4 + 3.i
!
.2099339 + .1681779i !
1.0436199 + 1.1924808i !
.4274910 + 1.5375701i !
.4652176 + 1.4896491i !
.8 + .2i
!
1.6236368 - .9896491i !
.1197226 + .7040707i !
.4452345 - .6924808i !
.1372797 - .6098187i !

In contrast, the equivalent SCILAB function fft, produces the inverse FFT of a two-dimensional spectra:
-->fft(w,1)
ans =

column 1 to 2
!
!
!
!
!
!
!
!
!
!

4.6333333
- .1351621
- .4343689
- 1.4822906
.2757102
- .3666667
.4381701
- .4436123
.2538220
.5943983

+ 4.1333333i
+ .5823058i
+ .6264648i
+ .5562064i
+ .4780715i
+ .4666667i
- 1.0664874i
+ .3025913i
- .1713823i
+ .4255631i

.9208119
.6511855
.7214139
.2105625
.1348462
.7565384
.1145707
.3729573
.3636599
.4835309

+
+
+
+
+
+
+

.2889958i
.1211742i
.1920704i
.6501190i
.0369391i
.4800641i
.8445391i
.0924896i
.1821964i
.5416909i

!
!
!
!
!
!
!
!
!
!

column 3
!
!
!
!
!
!
!
!
!
!

.1125215
.2444354
.0088104
- .7089849
- 1.0702188
.4101283
.1294004
- .2430592
.4611962
.4143427

+
+
+
+
+
+
-

.5776709i
.0025697i
.0898368i
.2800945i
.4399813i
.6532692i
.6651768i
.3565027i
.5686920i
.0260901i

!
!
!
!
!
!
!
!
!
!

mtlb_is
No information available on this function, except for the listing of the function itself in the sub-directory
macros\mtlb of the main SCILAB installation (e.g., c:\Program Files\macros\mtlb in Windows).

14

mtlb_ishold
Use this function in conjunction with function mtlb_plot to determine if a hold on plotting is active or not.
If function mtlb_hold() has been used, then function mtlb_ishold() returns the value of T (true). Otherwise,
function mtlb_ishold() returns the value of F (false).
mtlb_isreal
Produces a symbolic matrix with the result T (true) in element i,j if the corresponding element in the
argument matrix A is real. Otherwise, the result is the letter F (false). For example,
-->A = [1,3,5; 2, -%i,5]
A =
!
!

1.
2.

3.
- i

5. !
5. !

-->mtlb_isreal(A)
ans =
! T T T !
! T F T !
mtlb_length
To demonstrate the use of function mtlb_length first we create a column vector v and a row vector u, both
with six elements:
-->v = int(10*rand(6,1))
v =
!
!
!
!
!
!

3.
8.
5.
4.
2.
8.

!
!
!
!
!
!

-->u = int(10*rand(1,6))
u =
!

1.

2.

8.

8.

5.

9. !

Application of function mtlb_length to each of these vectors produces the vector length, i.e., the value 6, as
expected:
-->mtlb_length(u)
ans =
6.
-->mtlb_length(v)

15

ans

=
6.

SCILAB's function length produces the same result:


-->length(u)
ans =
6.
-->length(v)
ans =
6.
However, when applied to a matrix, function mtlb_length produces the number of columns of the matrix,
e.g.,
-->A = int(10*rand(5,3))
A =
!
!
!
!
!

6.
9.
0.
7.
4.

6.
8.
0.
8.
9.

5.
5.
8.
0.
5.

!
!
!
!
!

-->mtlb_length(A)
ans =
5.
SCILAB's length function, in this case, produces the number of elements of the matrix:
-->length(A)
ans =
15.
mtlb_load
Similar to SCILAB's load function. See help load for more information.
mtlb_loglog
Use function mtlb_loglog to produce a double-logarithmic plot. An example is shown below:
[1][2][3]-->x=[0.001,0.01,0.1,1.0,10.0,100.0];y=x^3;
-->mtlb_loglog(x,y)
-->xtitle('Log-log plot','x','y')

16

mtlb_max
This function allows you to calculate the maximum value in each column of a matrix,e.g.,
-->A = int(10*rand(5,3))
A =
!
!
!
!
!

8.
4.
4.
8.
1.

1.
5.
5.
6.
8.

5.
3.
3.
9.
9.

!
!
!
!
!

-->mtlb_max(A)
ans =
!

8.

8.

9. !

SCILAB's max function produces the maximum of the entire matrix:


-->max(A)
ans =
9.
mtlb_mean
This function can be used to obtain the arithmetical mean values of each column in a matrix:
-->A = int(10*rand(5,3))
A =
!
!
!
!
!

3.
3.
7.
2.
4.

2.
5.
5.
1.
2.

6.
7.
0.
6.
2.

!
!
!
!
!

17

-->mtlb_mean(A)

ans
!

=
3.8

3.

4.2 !

SCILAB's mean function produces the arithmetic mean of the entire matrix:
-->mean(A)
ans =
3.6666667
mtlb_median
This function can be used to obtain the median of each column in a matrix:
-->A = int(10*rand(5,3))
A =
!
!
!
!
!

3.
3.
7.
2.
4.

2.
5.
5.
1.
2.

6.
7.
0.
6.
2.

!
!
!
!
!

-->mtlb_mean(A)
ans =
!

3.

2.

6. !

SCILAB's median function produces the median of the entire matrix:


-->median(A)
ans =
3.

mtlb_mesh
Function mtlb_mesh can be used to produce a three-dimensional surface plot that emphasizes the
coordinate mesh in the final plot. The function produces a plot similar to that produced with function
plot3d.

-->deff([w]=f(x,y),w=sin(x)*cos(y))
--> x=[0:0.2:6];y=[0:0.2:6]; z = feval(x,y,f);
-->mtlb_mesh(x,y,z);

18

mtlb_meshdom
With the call [X,Y]=mtlb_meshdom(x,y), function mtlb_meshdom produces two dimensional matrices X
and Y out of the vectors x and y representing a grid in the x-y plane. For example,
-->x = [0:0.2:1], y = [0:0.5:2.5]
x =
!
y

0.
=

.2

0.

.5

.4

1.

.6

.8

1.5

2.

-->[X,Y] = mtlb_meshdom(x,y)
Y =
!
2.5
2.5
2.5
2.5
!
2.
2.
2.
2.
!
1.5
1.5
1.5
1.5
!
1.
1.
1.
1.
!
.5
.5
.5
.5
!
0.
0.
0.
0.
X =
!
0.
.2
.4
.6
!
0.
.2
.4
.6
!
0.
.2
.4
.6
!
0.
.2
.4
.6
!
0.
.2
.4
.6
!
0.
.2
.4
.6

1. !

2.5 !

2.5
2.
1.5
1.
.5
0.

2.5
2.
1.5
1.
.5
0.

.8
.8
.8
.8
.8
.8

1.
1.
1.
1.
1.
1.

These matrices can be combined with a random matrix, say,


-->Z = int(10*mtlb_rand(6))
Z =
!
!
!
!
!
!

1.
2.
3.
2.
3.
2.

2.
5.
2.
6.
5.
4.

4.
3.
5.
4.
9.
2.

4.
0.
2.
0.
7.
0.

3.
1.
2.
3.
7.
0.

9.
4.
2.
0.
8.
8.
19

!
!
!
!
!
!

!
!
!
!
!
!

!
!
!
!
!
!

to produce a mesh plot:


-->mtlb_mesh(X,Y,Z)

mtlb_min
This function calculates the minimum values in each of the columns of a matrix, e.g.,
-->A = int(10*rand(5,3))
A =
!
!
!
!
!

6.
4.
9.
0.
4.

2.
4.
2.
1.
7.

2.
1.
6.
1.
6.

!
!
!
!
!

-->mtlb_min(A)
ans =
!

0.

1.

1. !

SCILAB's min function obtains the minimum value of the entire matrix:
-->min(A)
ans =
0.
mtlb_mode
This function can be used to determine whether or not Matlab style of addition and subtraction of vectors
with the empty vector. By default the mtlb_mode is false:
-->mmode = mtlb_mode()
mmode =
F

20

Thus, adding an empty vector [] to another vector produces the second vector, i.e.,
-->[] + [2,3,5]
ans =
!

2.

3.

5. !

Changing the mtlb_mode to true by using:


-->mtlb_mode(%t)
produces an empty vector after adding the empty vector [] to another vector:
-->[] + [2,3,4]
ans =
[]
To return to original SCILAB setting use:
-->mtlb_mode(%f)

mtlb_ones
Used this function to produce a square matrix with all elements equal to 1, giving a single argument
representing the matrix dimension in one direction, e.g.,
-->mtlb_ones(2)
ans =
!
!

1.
1.

1. !
1. !

To produce the same matrix using SCILAB's ones function you would have to use:
-->ones(2,2)
ans =
!
!

1.
1.

1. !
1. !

mtlb_plot
The function mtlb_plot is similar to SCILAB's function plot. In its simplest form, the call mtlb_plot(x,y)
produces a continuous-line plot of vectors x and y of the same length as does plot(x,y). You can also
produce plots with symbols such as '+' or 'o' by using those strings as the third argument in the call to
function mtlb_plot. Two examples of mtlb_plot were presented when describing function mtlb_hold.
More examples are shown below. First, we generate some data by using:
-->x1 = [0:0.5:10]; y1 = sin(x1) + 2.5*sin(2*x1);
-->x2 = [0:1:10]; y2 = cos(x2) + cos(2*x2);
-->x3 = [0:0.2:10]; y3 = exp(-0.1*x3).*sin(x3);
21

Simplest

calls:

-->mtlb_plot(y1)

//Plots ordinate only uses plotting symbols.

-->mtlb_plot(x1,y1)

Call

//Plots (x,y) data uses a continuous line

includes specification for plotting symbol:

-->mtlb_plot(x1,y1,'*')

Other symbols available are 'o', and '+'.


22

The

color of the plotting symbols or lines can be changed by specifying one of the following colors:
r = red, g = green, b = blue, c = cyan. Try the following examples on your own:

-->mtlb_plot(x1,y1,'r')

//Continuous line in red color

-->mtlb_plot(x1,y1,'+r')

//Plus sign plotting symbol in red color

-->mtlb_plot(x1,y1,'xr')

//x plotting symbol in red color

-->mtlb_plot(x1,y1,'or')

//o plotting symbol in red color

An

example using mtlb_hold combined with mtlb_plot.

-->mtlb_ishold()
ans =

//checking conditions for hold

F
-->mtlb_plot(x1,y1,'r')

//Plot x1,y1, red continuous line

-->mtlb_hold()

//Set hold for multiple plots

-->mtlb_ishold()
ans =

//Check hold condition

T
-->mtlb_plot(x2,y2,'b')

//Plot x2,y2, blue continuous line

-->mtlb_plot(x3,y3,'*')

//Plot x3,y3, asterisks as plot symbols

-->xtitle('graph using mtlb_plot','x','y')

23

//Label plot

mtlb_prod
Function mtlb_prod is used to calculate the products of elements of each column in a matrix. For example,
A
!
!
!
!

=
4.
7.
1.
1.

5.
4.
6.
9.

0.
4.
9.
0.

9.
9.
9.
8.

!
!
!
!

-->mtlb_prod(A)
ans =
!

28.

1080.

0.

5832. !

In contrast, SCILAB prod function multiplies all elements in the matrix, e.g.,
-->prod(A)
ans =
0.
mtlb_qz
Function mtlb_qz is used to obtain the QZ factorization for generalized eigenvalues. With the call
[AA,BB,Q,Z,] = qz(A,B), for square matrices A and B, produces upper quasi-triangular matrices AA and BB,
and unitary matrices Q and Z such that Q*A*Z = AA, and Q*B*Z = BB. As an example, use:
-->[AA,BB,Q,Z] = mtlb_qz(A,B)
Z =
!
.6589552
! - .4020546
!
.6357123
Q =

.5836753
.2597769
.7693108

!
! !
BB

.5404057
.4031014
.7385600

.2514085
.7603132
.5989303
=

.4744483 !
.8779909 !
.0634880 !

.8029666 !
.5093457 !
.3095345 !

! - 2.1943415
!
0.
!
0.
AA =

2.222851
- 7.9095326
0.

- 6.0820818 !
- .8019976 !
9.2762154 !

! - 2.0841206
!
0.
!
0.

- 2.1146607
.8229329
0.

.2138868 !
- 1.3430324 !
4.0814151 !

In SCILAB, the results of function mtlb_qz can be accomplished with SCILAB function gschur:
24

-->[AA,BB,Q,Z] = gschur(A,B)
Z =
!
.6589552 - .5836753
! - .4020546
.2597769
!
.6357123
.7693108
Q =
!
! !
BB

.2514085
.7603132
.5989303
=

.5404057
.4031014
.7385600

.4744483 !
.8779909 !
.0634880 !

.8029666 !
.5093457 !
.3095345 !

! - 2.1943415
2.222851
!
0.
- 7.9095326
[More (y or n ) ?]
!
0.
0.
AA =

- 6.0820818 !
- .8019976 !

! - 2.0841206
!
0.
!
0.

.2138868 !
- 1.3430324 !
4.0814151 !

- 2.1146607
.8229329
0.

9.2762154 !

mtlb_rand
The call mtlb_rand(n) produces a matrix of random number of dimensions nxn. Using SCILAB's rand
function, the equivalent call would be written rand(n,n). For example,
-->mtlb_rand(4)
ans =
!
!
!
!

.3950498
.0366117
.5175369
.8325452

.6104832
.1871112
.0189575
.8433565

.0748595
.8532815
.0124590
.1867539

.4920584
.7489608
.9414957
.2124056

!
!
!
!

The call mtlb_rand(m,n) produces a three-dimensional array consisting of n two-dimensional arrays of


dimensions mxm. For example,
-->mtlb_rand(2,1)
ans =
(:,:,1)
!
!

.8191490
.1304993

.9682004 !
.6561381 !

Also,
-->mtlb_rand(3,2)
ans =
(:,:,1)

25

!
.2445539
!
.5283124
!
.8468926
(:,:,2)

.7876622
.1262083
.7883861

.3453042 !
.2659857 !
.9709819 !

!
!
!

.6744698
.9152874
.0284860

.2367841 !
.7015344 !
.1202527 !

.8875248
.2066753
.8525161

mtlb_save
Similar to SCILAB's function save. Use help save for more details on using the save function.

mtlb_semilogx
Use function mtlb_semilogy to produce a semi-logarithmic plot with the logarithmic scale located in the yaxis.
-->x=[0.001 0.01 0.1 1.0 10. 100]; y=[20 30 40 50 60 70];
-->mtlb_semilogx(x,y)
-->xtitle('Logarithmic scale in the x axis','x','y')

mtlb_semilogy
Use function mtlb_semilogy to produce a semi-logarithmic plot with the logarithmic scale located in the yaxis.
-->x=[1:0.1:10];y=2*x^2;
-->mtlb_semilogy(x,y)
-->xtitle('Logarithmic scale in y','x','y')

26

mtlb_subplot
The function mtlb_subplot can be used to produce multiple plot frames in the same window. The call to
mtlb_subplot is mtlb_subplot(m,n,j)
The effect of this function is to split the plot area in a window into a graphics matrix of m rows and n
columns, making the sub-area j available for plotting. The values of j range from 1 to p = mn, with
subplot j=1 corresponding to the upper left corner of the window, subplot j=2 being the next subplot to the
right, j=3 the next subplot to the right until reaching j=m. Subplot j=m+1 is the first subplot in the second
line, and so on. The position and numbering of the subplots is shown in the next sketch.

Thus, the plot at location (i,k) is subplot number j = (i-1)m+k. To fill the window with plots you need to
call function mtlb_subplot a total of p times using fixed values of m and n and varying j according to the
position of the plot.
An example of application of function mtlb_subplot is provided next in the form of a SCILAB script:
//Script to produce four plots in the same window
x=[0.0:0.1:1.0];y=x^2;z=sin(x)+sin(2*x);t=(1./(1+x))';r=abs(x-0.5);
mtlb_subplot(2,2,1);plot2d(x,y,-2);xtitle('Plot 1','x','y');
mtlb_subplot(2,2,2);plot2d(x,z,-1);xtitle('Plot 2','x','z');
mtlb_subplot(2,2,3);plot2d(x,t,-9);xtitle('Plot 3','x','t');
mtlb_subplot(2,2,4);plot2d(x,r,-5);xtitle('Plot 4','x','r');
The result of the script is shown next:
27

mtlb_sum
Produces column sums of a matrix. For example, for the following 3x3 matrix
-->A = int(10*rand(3,3))
A =
!
!
!

3.
2.
5.

4.
3.
5.

5. !
4. !
2. !

mtlb_sum produces the vector:


-->mtlb_sum(A)
ans =
!

10.

12.

11. !

SCILAB's sum function, on the other hand, adds all elements in the matrix, i.e.,
-->sum(A)
ans =
33.
mtlb_zeros
Used this function to produce a square matrix with all elements equal to zero, giving a single argument
representing the matrix dimension in one direction, e.g.,
-->mtlb_zeros(2)
ans =
!
!

0.
0.

0. !
0. !

28

To produce the same matrix using SCILAB's zeros function you would have to use:
-->zeros(2,2)
ans =
!
!

0.
0.

0. !
0. !

_______________________________________________________________________
This document was prepared by Gilberto E. Urroz, August 10, 2001.

29