0% found this document useful (0 votes)
235 views

Getting Started With Scilab-Seminario

This document provides a syllabus for a course on getting started with Scilab. The syllabus covers topics like the Scilab environment, matrices, plotting graphs, functions, and reading Excel files. It also includes tasks for downloading and installing Scilab, and joining an online community for Scilab users.

Uploaded by

Hugh cab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
235 views

Getting Started With Scilab-Seminario

This document provides a syllabus for a course on getting started with Scilab. The syllabus covers topics like the Scilab environment, matrices, plotting graphs, functions, and reading Excel files. It also includes tasks for downloading and installing Scilab, and joining an online community for Scilab users.

Uploaded by

Hugh cab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Syllabus for Getting Started with Scilab

This is the Syllabus for the Getting Started with Scilab course:

1. Scilab environment
2. Scilab as an interactive calculator
3. Scilab workspace and working directory
4. Creating matrices and some simple matrix operations
5. Sub-matrices
6. Statistics
7. Working with polynomials
8. Plotting graphs
9. Scilab programming language
10. Script files and function files
11. Writing Scilab functions
12. File operations
13. Reading Microsoft Excel files
14. Data Structures

You can download the free PDF document Scilab - A Hands on Introduction from
Lulu, which is the base document for this course.
Task Discussion
Task 1: Downloading and installing Scilab

Task
Download and install Scilab for your operating system
Task deadline
May 25, 2011 before course commences
Downloading
First task is to download Scilab on your system. A version of Scilab starting from
5.2 is desirable. If Scilab is alrady installed on your system there is nothing more to
do to accomplish this task, but you may review the syllabus of this course and see
if you still wish to continue with the course.

Scilab is available as installable binaries for Windows, GNU/Linux and MacOS X.


Source coude is available and can be compiled for these or other platforms, but
that is beyond me.

These are the sources from where you can download Scilab binaries:

1. Download from Scilab website and install


2. If you are using GNU/Linux, your repository may have Scilab and you
could install it using your package manager (apt-get or synaptic on
Debian/Ubuntu, yum on Fedora etc.). Note: Your software repository may
not have the most recent version.

Download from Scilab Website and Install


Scilab software can be downloaded from the Scilab website. You can directly visit
the download page. Current version, as of this writing is 5.3.2. Installable binaries
are available for Windows (both 32 and 64 bit versions), Linux (both 32 and 64 bit
versions) and MacOS X. Choose the operating system appropriate to you.
Download and install on your system.

Note: It is not necessary that you have this same version of Scilab for the purpose
of this course. Even a previous version as old as 4.2 (if already installed on your
system) is good enough. However, Scilab has made great improvements to the
user interface starting from version 5.2. Especially the editor to write Scilab
functions and programs, variable inspector window, dockable windows are very
good.

Downloading using your Package Manager


On Ubuntu, Scilab is available from the Universe repository. In Synaptic Package
Manager main menu, Settings -> Repositories make sure Community-
maintained open source software (universe) is selected. Then update the
repositories and search for Scilab. Select Scilab and install.
Installing Scilab

Windows
Execute the downloaded executable file and follow instructions. Choosing all
default choices during installation is good enough.

GNU/Linux
If you downloaded the binary from Scilab website, it is in the form of
a tar.gz compressed archive. Expand it into a directory of its own, preferably /opt,
and execute the scilab-bin script in the bin directory under the directory where
you expanded the downloaded compressedd archive. Create a link on the desktop
or in the Applications menu, if you want a quick way of launching Scilab.

If you installed using your package manager, there will be a link to Scilab in your
menu. In Ubuntu, it is under Applications -> Programming.
Screencast
Watch this screencast on YouTube
Task Discussion
Task 2: Join Equalis community

Equalis is a vibrant online Math community. They provide a full rnage of Scilab
support and membership to the community is free.

If you are not already a member, join now. You can join a number of Groups within
the Equalis community, including Scilab. Equalis website is
at http://www.equalis.com. Join the Scilab group and watch the recorded Scilab
webinar.

Task Discussion

Anonym Nov. 6, 2011, 9:18 p.m.


The webinar is no longer available.

Satish Annigeri Nov. 6, 2011, 9:33 p.m.


In Reply To: Anonym Nov. 6, 2011, 9:18 p.m.
I am sorry the webinar has moved. Here is an alternative. After creating your
account on Equalis, join the Scilab group. You will find a link on the Scilab Group
page: https://www.equalis.com/page/Scilab_Video_511. You could find other
material on the same page.

Regards.

Satish Annigeri
Session 0: Scilab - History, Features and Applications

Objectives
• Understand the history of Scilab
• Learn about key features of Scilab
• List the fields where Scilab can be applied

History of Scilab
• Scilab was created in 1990 by researchers from INRIA and ENPC.
• Scilab Consortium was formed in 2003, to broaden contributions and
promote its use in academia and industry worldwide.
• Scilab adopted the CeCILL license in July 2004, which is compatible with
the GNU GPL.
• In July 2008, Scilab Consortium joined Digiteo, a research cluster in
Information Science & Technology.
• In June 2010, Scilab Consortium announced the formation of Scilab
Enterprises to broaden contributions to Scilab and promote its use in
academis and industry worldwide.
• The lastes version of Scilab is 5.3.2 released on May 12, 2011

Key Features of Scilab


• Maths and Simulation: Elementary mathematics, Liner Algebra, Sparse
matrices, Polynomials, Ordinary differential equation solvers
• 2D and 3D visualization: Graphs of 2D and 3D functions and data, Contour
plots, LaTeX and MathML annotations, export to various graphic formats
• Built-in interpreted programming language with access to all Scilab functions
• Optimization: Nonlinear optimization, Quadratic optimization, Semi-definite
programming, Genetic algorithms, Simulated annealing
• Control Systems Analysis and Design: Transfer function, Classic and robust
control, State-space control system design
• Signal processing
• Application design: Advanced data structures, User defined GUI, Interface
with Fortran, C/C++, Java, Embedding Scilab in C/C++, Java, .NET,
Dynamic build, link and testing framework
• Export and Import: Matlab to Scilab code translator, Read and write MS
Excel files

Applications of Scilab
This list would have to be based on my limited experience and knowledge and
hence would necessarily be incomplete. In fact, it is is a futile exercise attempting
to prepare such a list. Rather, it would be better to say that Scilab can be used
wherever one needs a matrix numerical computation tool with an ability to visuaize
data. So I will not attempt to prepare such a list.
Useful Links
• Wikipedia article on Scilab
• On Scilab website
o Key facts about Scilab
o Key features of Scilab
o Scilab license
o Xcos
o Scilab versions
o Scilab modules
• Free Software Foundation analysis of CeCILL license

Task Discussion

Satish Annigeri May 24, 2011, 10:50 p.m.


Comments on Session 0: Scilab History, Features and Applications are
welcome. You are encouraged to comment, add, delete and improve the content.
Participants are allowed to not only comment on the content, they are also allowed
to edit the content.


Anonym May 23, 2011, 4:01 a.m.
Do any major companies use this software?

Satish Annigeri May 23, 2011, 8:18 a.m.


In Reply To: Anonym May 23, 2011, 4:01 a.m.
The following link will give you the list of members of Scilab
Consortium http://www.scilab.org/aboutus/consortium/members. To be members,
they must have an interest in the software and will have paid some fees. So I
assume they are using it. I believe it is being used in European industries and
Scilab Consortium has made concerted efforts, since 2005 I think, to see that it is
adopted by industries.

Matlab is the de-facto industry standard, but I think Scilab is a viable alternative at
least for some applications. Where it beats Matlab is in the fact that you have
access to its source code. So either you, or someone you employ, can modify
Scilab to add features to your exact requirements. And other users get the benefit
of your contributions.

See NI LabView to Scilab gateway project


(http://www.scilab.org/projects/collaborations/ni) and ProActive parallel suite
(http://www.scilab.org/projects/collaborations/proactive) collaboration for some
examples of the advantages of FOSS. Also see Google Summer of Code
(http://www.scilab.org/projects/development/google) for some student projects.
Session 1: Scilab Environment

Objectives
A beginner is usually apprehensive when starting to learn a new software. The best
way to get acquainted with a new software is to study its working environment and
learn how to get help in learning the software. The best form help is online help
that the software offers right there on the screen. Next, you must learn a few
shortcuts that make working in the software easy and quick.

In this session you will learn the following:

1. Visible components of Scilab, the Scilab console


2. Invisible component of Scilab, the Scilab workspace
3. Invoking online help
4. Working in Scilab console
5. Closing Scilab session

Visible Components of Scilab Environment


When you start Scilab, you see the Scilab console, with the command prompt
waiting for you to type a valid Scilab command. In addition to the console, Scilab
has other environments, namely:

1. Editor (called SciNotes),


2. Variable Browser and Editor,
3. History Browser,
4. Scilab Help,
5. ATOMS (AuTOmatic Modules Management for Scilab) and
6. Xcos.

Note:

1. Variable Browser and Editor, History Browser and ATOMS were


introduced in Scilab version 5 and are not available if you are using an
older version of Scilab.
2. Xcos is the revamped replacement for Scicos of the older versions of
Scilab.
When you start Scilab, only the console is open and the other environments are
not. Choose the environment you want to use from the Main
Menu under Applications.

It is possible to dock all these environments into the console window by dragging
the environment you wish to dock and dropping it into place in the console.
However, a beginner will take some time to master this operation.

For more details about these environments, visit this link on the Scilab website.
Invisible Components of Scilab Environment
While the above are the visiblle components of Scilab environment, there is the
invisible component of Scilab, the Scilab Workspace. Workspace is the memory
space where Scilab stores its environment variables, constants, variables,
compiled functions and libraries. The Variable Browser and Editor offers a view of
the Workspace contents, it shows only the environment variables, constants and
variables but not the functions and libraries. Further, it does not permit clearing
variables from the Workspace. Thus, until it is improved, we will view and
manipulate the Workspace using commands such as who, whos, clear, save, load
etc.
Invoking Online Help in Scilab
Scilab provides online help in a browser like environment, and is similar to the
online manual of *nix, namely, man. Help can be invoked in a number of ways:

1. Use mouse to choose Main Menu -> ? -> Scilab Help


2. Type F1 from the console
3. Command help <cr> typed at the command prompt. This opens the
Scilab Help browser where you can browse through the Table of Contents
or use the Search feature.
4. Command help pattern <cr> typed at the command prompt. This opens
the Scilab Help browser and shows all commands or contents matching
the patterns you entered.

Working with Scilab Console and Some Useful Console


Shortcuts
Scilab console is similar to the terminal in *nix or MS DOS Prompt of Windows. It is
a shell that interprets the command typed by the user, executes the command and
displays the results.

1. Scilab commands are case sensitive. the characters A and a are distinct.
2. To let Scilab console know the command is complete, press the Enter
key. Only then does the command get executed.
3. If you type a command that Scilab does not understand, it will display an
error message.
4. Commands you type may be names of variables, names of Scilab
functions or names of user defined functions currently loaded into Scilab
Workspace (we will see how to do this when we discuss Scilab functions
in a later session)

A beginner should quickly master the following things to become comfortable


working in the Scilab console:

1. To clear the screen type the clc <cr> at the command prompt or simply
press the F2key.
2. To abort a command midway without executing it, press the Esc key on
the keyboard.
3. Scilab offers command completion, similar to the feature available
in bash shell in *nix (Unix, Linux). Press the Tab key to use the command
completion feature. You will be shown a list of commands matching the
pattern already typed and you can scroll through the list and choose one
of them or type more characters to reduce the list of matching commands.
4. A history of previous commands is stored and you can scroll through this
history by pressing the Up or Down arrow keys on your keyboard.
Alternately, you can open the History Browser environment. You can edit
any previous commands using Left Arrow, Right
Arrow, Home and End keys to move about the command
and Backspace and Del keys to delete characters and you can type in
new characters. This feature is again similar to the one in bash shell.

Closing Scilab
You can close Scilab in one of the following ways:

1. Type the exit <cr> or quit <cr> command at the command prompt.
Actually, quit either terminates the Scilab session or decreases the pause
level. Thus, if you have paused the session, you may not actually
terminate the session.
2. From the main menu, choose File -> Quit.
3. Click on the Close button on the Scilab console window.

Screencast
Watch the screencast on YouTube
Task Discussion

Anonym Nov. 7, 2011, 7:40 p.m.


Suppose you defined a function. Does it get erased when you clear the screen
or does it remain in the memory?

Satish Annigeri Nov. 7, 2011, 8:02 p.m.


In Reply To: Anonym Nov. 7, 2011, 7:40 p.m.
Clearing the screen (clc) does not erase the defined function. It only clears the
screen. It is more important to know what happens when you quit Scilab.

If you define a function by typing it at the Scilab console, it is stored in the Scilab
workspace and is erased when you quit Scilab.
An alternate, and better approach, would be to write the function in SciNotes
(Console Main Menu -> Applications -> SciNotes), load it into Scilab Workspace
(SciNotes Main Menu -> Execute -> with echo) and save the function to a disk file
(SciNotes Main Menu -> File -> Save). To execute the function the next time, start
Scilab, open SciNotes, load the function file (SciNotes Main Menu -> File -> Open)
and load the function into Scilab workspace.
Regards.
Satish Annigeri

Anonym May 25, 2011, 4:44 p.m.


I'm not getting sounds in the video. Is that how its supposed to be?

Satish Annigeri May 25, 2011, 8:44 p.m.


In Reply To: Anonym May 25, 2011, 4:44 p.m.
Yes, the screencasts have no audio (including the ones in subsequent sessions).
Sorry. I have used comments at the end of the commands to indicate what is being
done.

Antonio Neves May 24, 2011, 7:39 p.m.


I liked the Google Summer of Code for Scilab, in the end are these projects open
source?

Satish Annigeri May 24, 2011, 7:58 p.m.


In Reply To: Antonio Neves May 24, 2011, 7:39 p.m.
All projects are open source. See here http://www.google-
melange.com/gsoc/projects/list/google/gsoc2011 for the list of all GSOC projects,
of which you will see Scilab projects too.

Satish Annigeri May 26, 2011, 11:43 a.m.


In Reply To: Antonio Neves May 24, 2011, 7:39 p.m.
Yes. Google supports open source through stipends to students who want to work
on open source projects under mentorship of developers already wroking on these
projects. Visit the following URL for a list of proposals accepted this
year: http://www.google-melange.com/gsoc/projects/list/google/gsoc2011
Session 2: Scilab as an interactive calculator

Objectives
Having explored the Scilab environment and user interface, you are now ready to
get down to business - doing some calculations. If you have used any
programming language before, you will be familiar with expressions, statements,
variables and constants. If not, nothing to worry, they are not that difficult to
master.

In this session you will learn the following:

1. Using Scilab interactively to perform simple arithmentic operations


2. Writing expressions and statements
3. Creating and using variables
4. Using Scilab built-in constants
5. Using Scilab environment variables

Interactive Calculations using Scilab


If you have used a calculator before, you will be at home in the Scilab console
environment. Just type the mathematical expressions you wish to calculate. All
arithmmetic operations such as addition, subtraction, multiplication, division,
exponentiation etc. are readily available. Operator precedence, use of parentheses
to correctly evaluate expressions are all as you would expect on a calculator. So,
try out the following:

-->2 + 3

ans =

5.

Let me point out a few things to clarify what happened:


1. At the command prompt, you entered the expression 2 + 3 and pressed
the Enter key
2. Scilab responded with the answer 5.
3. Scilab used a built-in variable named ans to store the result of the
expression you typed, because you did not supply a variable to store the
result
4. The result is a real number (note the decimal after 5) even though the
numbers added were integers. In Scilab, all numbers are by default real
numbers, unless they happen to be imaginary numbers. There are no
numeric types such as integers, float, double etc as in other programming
languages. All numeric types are double precision real numbers (Scilab
does allow integers int8, int16, int32, uint8, uint16, uint32, but they are
rarely used)

Let us repeat the same expression with a small change.

-->x = 2 + 3

x =

5.

This time, the result of the expression was stored in the variable x, as specified by
you and the result was echoed on the console. Let us now try another simple
calculation.

-->y = 2 * 3;

-->y

y =

6.
This time, you are attempting a multiplication and have specified that the result be
stored in a variable named y. Note the semicolon (;) at the end of the expression.
Putting a semicolon at the end of an expression suppresses the display of the
result, but the statement is evaluated and result is stored in y. You can verify that
by typing the next statement at the command prompt where you type the name of
the variable whose value you want to display. Scilab responds by displaying the
value of y.

Important Note
Scilab language is weakly typed. That is:

1. It is not necessary to declare a variable before being able to use it. In a


strongly typed programming language such as C, a declaration makes
known to subsequent parts of the program, the name and type of a
variable.
2. It is possible to alter the type of a variable at anytime, as long as you, the
programmer, know what type it is at the instant when it is used. In a
strongly typed programming language, type of a variable cannot be
altered once it is declared.

Multiple Statements on One Line


You can type multiple statements on one physical line by separating each
statement from the next with a comma or a semicolon. Results of statements
followed by a comma are displayed while those of statements followed by
semicolon are suppressed. Try out the following:

-->a = 10 - 5, b = 3 / 4; c = 2^3

a =

5.

c =

8.
One Statement on Multiple Lines
Values of a and c are displayed while that of b is not. By the way, operator for
exponentiation is ^. Just as you can put multiple multiple statements on a single
physical line, you can also split a long statement (or even a short one, if you so
wish) on multiple physical lines. Try out the following:

-->a = 2 + ...

-->5 * 2

a =

12.

Let us summarize:

1. We used the following operators: +, -, *, /, ^


2. If the user does not specify a variable to store the results of an
expression, Scilab uses its built-in variable ans. Corollary: Do not use
the name ans as the name of one your own variables, it is reserved for
use by Scilab.
3. A semicolon at the end of an expression suppresses the display of the
result of that statement.
4. Multiple statements on the same physical line can be separated by either
a comma or a semicolon. Results of statements followed by a semicolon
are not displayed.
5. A statement can be split on to multiple lines by ending the line with three
consecutive dots (...). Then the subsequent line is treated as a
continuation of the statement on the previous line.
6. All numbers are double precision real numbers or imaginary numbers.

Built-in Constants
Scilab predefines commonly used constants so that they are readily available to
the user. Names of all constants can be easily recognized as they start with the
precent (%) symbol. Available constants are:
1. Pi - %pi
2. e - %e
3. sqrt(-1) - %i
4. Infinity - %inf
5. Not a number - %nan
6. True - %T or %t
7. False - %F or %f

Use the Variable Browser environment to see a list of constants in the Scilab
Workspace. Use the online help to learn more about some of the constants.
Environment Variables
Scilab uses a few environment variables for its internal use and their values are
initialized when Scilab starts. Environment variables are by convention in all
uppercase letters. If you know *nix operating systems, you will immediately notice
the resemblance to the bash and other shells. To see the value assigned to an
environment variable, just type its name at the command prompt. To know the
names of environment variables, open the Variable Browser and search for names
in all capitals.

Some useful Environment Variables you must know are:

1. SCIHOME - Name of the directory where Scilab configuration files for the
user are stored. On Windows, it will be somewhere within the users Home
directory. For example, on a Windows 7 machine, SCIHOME may be
C:\Users\<Username>\AppData\Roaming\Scilab\Scilab-5.3.1. On a Linux
machine, it might be /home/<username>/.scilab (Note: In the place of
<Username>, the actual username will appear)
2. TMPDIR - Directory where Scilab stores temporary files
3. SCI - Directory where Scilab is installed. On Windows, it is in DOS
filename convention of 8.3 characters.
4. WSCI - Directory where Scilab is installed, in Windows filename
convention.
5. MSDOS - Boolean constant set to True if Scilab is running in Windows
operating system.

Built-in Mathematical Functions


We can now move on to using some built-in mathematical functions, such as,
trigonometric, logarithmic, hyperbolic etc. When using trigonometric functions,
remember that all angels are in radians. If you wish to use angles in degrees, take
care to convert them to radians before using them. Or, Scilab has a set of functions
that take angles in degrees.

Here are the functions you are likely to use often:

Trigonometric Functions

1. sin(), cos(), tan() - angle must be input in radians.


2. sind(), cosd(), tand() - angle must be input in degrees.
3. asin(), acos(), atan() - Inverse trigonometric functions. Return angles in
radians.
4. asind(), acos(), atand() - Inverse trigonometric functions. Return angles in
degrees.

Logarithmic Functions

1. log(), log10() - Natural logarithm, Logarithm to base 10


2. exp() - Anti natural logarithm

Hyperbolic Functions

1. sinh(), cosh(), tanh()


2. asinh(), acosh(), atanh()

Defining and Using Variables


Scilab is more like programmable calculator rather than a simple one. It can define
variables, assign them values and use the variables as part of expressions and
statements. The rules for choosing names of variables are similar to those in other
programming languages and are:

1. Name of a variable must consist of alphanumeric characters


2. First character must be an alphabet
3. Underscore character is treated as an alphabet
In addition to the above rules, it is convention to adopt the following guideline even
though not following them is syntactically accepted:

1. Choose names to be both short as well as self explanatory. How you


achieve these contradictory goals is a matter of practice.
2. separate words in a multi-word name by underscore character or use
CamelCase

Let us try this out:

-->a = 2; b = 3; c = -4;

-->disc = b^2 - (4 * a * c)

disc =

41.

-->r1 = (-b + sqrt(disc)) / (2 * a), r2 =(-b + sqrt(disc)) / (2 * a)

r1 =

0.8507811

r2 =

-2.3507811

This is what we did:

1. Created three variables named a, b and c and initialized them with values
2, 3 and -4 respectively.
2. Evaluated the expression b^2 - 4ac and assigned the result to a new
variable disc.
3. Evaluated the expressions (-b + sqrt(disc))/(2a) and (-b - sqrt(disc)) / (2a)
and assigned the values to two new variables r1 and r2 respectively.

The workspace now contains all these variables and can be used in subsequent
expressions or statements.
Screencasts
Watch the following two screencasts, but before that, a note - I have used
comments in the screencasts to explain what is being done because I could not
record voice. When you try out the commands, you need not type the
comments. In Scilab, comments begin with two forward slashes and end with
the end of the line.

• Part 1: Interactive session in Scilab


• Part 2: Interactive session in Scilab showing determination of roots of a
quadratic equation

Exercises
1. Discover other functions and what they do using Scilab Help browser.
2. Discover other operators, especially boolean operators, using Scilab Help
browser. Prepare a list of Scilab operators, especially boolean operators,
which are usually neglected.
3. Discover other constants using Variable Browser. Prepare a list of Scilab
constants.
4. Prepare a list of Scilab environment variables.

Task Discussion
Session 3: Workspace and Current Working Directory

Objectives
Once you have done a few calculations in the Scilab console, you are now ready to
explore the invisible environment of Scilab, its Workspace. Learning to explore and
manipulate the Workspace is necessary as it gives you an insight into how Scilab
works on the inside.

In this session you will learn the following:

1. Commands to explore the Workspace


2. Commands to manipulate the Workspace - save, clar and load variables
3. Current Working Directory, its importance, querying its current setting,
changing it to another directory

Commands to Work with the Scilab Workspace


Before Scilab introduced the Variable Browser environment (Scilab versions up to
4), the only way to inspect and manipulate the Scilab Workspace was through the
set of commands dedicated for that purpose. However, starting with Scilab version
5, Variable Browser provides a visual interface to examine and change Scilab
Workspace and manipulate the values of the variables stored in the Workspace.
Currently, the Variable Browser only shows Scilab Environment Variables,
constants and variables. Functions and libraries loaded in the Workspace are not
displayed. Further, while it is possible to change the values of the variables, it is
not possible to clear the variables from the Workspace. Thus, knowing Scilab
commands continues to be an advantage since the Variable Browser still lacks
some features.

The commands that we will study in this session are:

1. who: Displays the names of items in the Workspace


2. whos: Displays a detailed list of items in the Workspace, including their
name, type, size (rows and columns) and memory used (in bytes)
3. whos -name pattern: Same as whos, but filters the names of objects
according to the specified pattern
4. whos -type objtype: Same as whos, but filters the names of objects
based on the specified objtype.
5. save: Save variables in the Workspace to a file on disk. Usage --
>save(filename) saves all user define variables in the workspace to the
file specified by the string filename. For further explanation about the file,
see the next discussion in this session.
6. load: Load variables from a file on disk to Workspace
7. clear: Erase variables from the Workspace

Important Note
Comments in Scilab console or Scilab script files are initiated with two forwards
slashes. Comments last up to the end of the line where they begin. Therefore, if
you see a comment in the commands described below, they need not be typed.
They are only to explain the purpose of the command, or what to expect from the
output. While you need not type them, reading and understanding them is very
helpful in learning.

Here is an example:
-->SCIHOME // Displays Scilab Home Directory

Examples
Display the entire content of the Workspace
-->who

The above command lists only names of objects in the Workspace. Their type, siz
and memory used are not listed. Filtering the output based on name is not
possible.

Display detailed information about the contents of the Workspace


-->whos

The above command lists all the objects in the Workspace and displays the name,
type, size and memory used by each object.

Filter the detailed list based on names of objects


-->whos -name a
The above command displays a detailed lists of only those objects in the
Workspace whose name begins with the letter a.

Filter the detailed list based on type of objects


-->whos -type constant

The above command displays a detailed list of only those objects whose type
is constant. To find the other types available in Scilab, search Scilab Help
for typeof. Some other types available in Scilab are polynomial, function, handle,
string, boolean, list, rational, library etc.

Important Notes:

1. You can only filter based on one of the above criteria. It is an error to
specify both criteria simultaneously.
2. Filter pattern for object names mathches only the beginning of the name.
Wildcard patterns are not possible (for example * or ? used in matching
filenames in bash shell)

Screencast
Watch the screencast on YouTube. (There is no audio. Read the comments. No
need to type the comments when you try out the commands)
Current Working Directory
When Scilab starts, it sets your Current Working Directory. The directory set as
your working directory may depend on your operating system. But you can always
enquire and find what your Current Working Directory is. Not just that, you can
change your Current Working Directory to any directory you want. The importance
of the Current Working Directory is that it is the default location from where Scilab
will read files from (or write files to) when the filename you specify during readin (or
writing) is not an absolute path.

What is an Absolute Path?


On Windows operating system, a path starting with the drive letter is an absolute
path. Thus C:\Users\Satish\My Documents\Scilab\test.sce is an absolute path
specification because it begins with the drive letter C:. test.sce is the file name
and C:\Users\Satish\My Documents\Scilab\ is the path. This path specification is
an absolute path specification. On the
otherhand, test.sce, ../examples/test.sce are relative path specifications.

On *nix operating systems, an absolute path specification begins with the root of
the file system, namely the forward slash (/).
Thus, /home/satish/Documents/Scilab/test.sce is an absolute path specifications
whereas test.sce or ../examples/test.sce are relative path specifications.

Relative path specifications specify the location of a file relative to the Current
Working Directory.

Displaying the Current Working Directory


-->pwd

-->pwd()

Both the above commands display the Current Working Directory being used by
Scilab at that instant of time. The first is a function pointer and the second is a
function. Even though both display the Current Working Directory, the type of
return values are different. You can test it with the following commands:
-->typeof(pwd)

ans =

fptr

-->typeof(pwd())

ans =

string

-->WSCI == pwd()

ans =

-->WSCI == pwd

!--error 144

WSCI is a constant of type string whose value is the directory where Scilab is
installed. pwd() returns a string and hence the boolean comparison is possible.
The result may be either T or F depending on the values of WSCI and pwd().
But pwd is of fptr and therefore the boolean comparison results in an error.

Screencast
Watch the screencast on YouTube. (No audio. Read the comments. No need to
type the comments when you try out the commands)
Changing the Current Working Directory
You can change the Current Working Directory used by the Scilab session with the
commands cd or chdir. Alternately, you can use the Main Menu File --> Change
current directory visually using a dialog box.

On Windows operating System use:


-->cd('C:\Users\Satish\My Documents\Scilab')

-->chdir('C:\Users\Satish\My Documents\Scilab')

On *nix operating systems use:


-->cd('/home/satish/Documents/scilab')

-->chdir('/home/satish/Documents/scilab')

Changing the Current Working Directory is much easier, especially for a beginner
and when the directory path is very long if you use the dialog box available in the
Main Menu File --> Change current directory.

Screencast
Watch the screencast on YouTube (No audio. Read the comments. No need to
type the comments when you try out the commands)

Where Does Scilab Save My Files?


If you specify the absolute path to the file, it will be saved indicated by your path
specification. If you specify the relative path to the file, it will be saved to the
current working directory.

From Where Does Scilab Read My Files?


If you specify the absolute path to your file, it will be read from the location
indicated by your path specification. If you specify the relative path to the file, it will
be read from the Current Working Directory.
Saving Contents of the Workspace

Saving all variables to a file in the Current Working Directory


-->save('test.dat')

Saving all variables to a file in a directory of your choice


-->save('D:\Scilab\Project\test.dat') // These are comments. No need
to type them. Windows operating system

-->save('~/prj/test.dat') // *nix operating systems

Saving selected variables to a file in the Current Working Directory


-->save('test.dat', x, y, z) // x, y and z are the variables you wish
to save to the file

Saving selected variables to a file in a directory of your choice


-->save('D:\Scilab\Project\test.dat', x, y, z)

-->save('~/prj/test.dat', x, y, z)

Loading variables from a file into the Workspace


-->load('test.dat') // Be sure to set Current Working Directory befor
e using this command

-->load('C:\Users\Satish\My Documents\Scilab\test.dat') // Windows. L


ong path spec!

-->load('~/Scilab/test.dat') // *nix

Clearing Variables from the Workspace

Clearing selected variables from the Workspace


-->clear x y z // clear only selected variables. NOTE NO COMMAS

Clearing all variables from the Workspace


-->clear // Clears all variables! Dangerous! Be sure you want to do t
his

Demonstrate save(), clear and load() work


-->// Create some variables and initialize them

-->a = 10; b = rand(3,4) * 100; c = sin(b);

-->//Verify that they exist in the Workspace

-->a, b, c

-->// Take note of your current working directory

-->pwd

-->// Save variables a, b and c to disk file test.dat in current work


ing directory

-->save('test.dat', a, b, c)

-->// Kill variables a nd b. NOTE, NO COMMA

-->clear a b

-->// Display variable a. ERROR, no variable a in workspace

-->a

-->// Ditto, variable b

-->b

-->// We didn't kill variable c. It will be displayed

-->c

-->// Kill variable c

-->clear c

-->// ERROR
-->c

-->// Load variables a, b and c from disk file test.dat in current wo


rking directory

-->load('test.dat')

-->// Whew, back to normal again

-->a, b, c

Important Notes

1. In the clear command, do not use comma to separate names of variables


to be killed, separate them by whitespace. Comma is interpreted as end
of statement, not as a separator.
2. It is a good habit to always note the Current Working Directory as soon as
you start a Scilab session, and change it to whatever you want right in the
beginning.
3. You can customize the Current Working Directory. See the section below.

Screencast
Watch the screencast on YouTube. (No audio. Read the comments. No need to
type the comments when you try the commands)
Customizing Scilab using Startup File
Scilab searches for a startup file when it starts, and executes the commands in that
file. So customize this startup file to your requirements (create it if does not exist).
The things you should know to do this successfully are:

1. Location of the startup file and its name


2. The commands you wish to put in this startup file

Location and name of startup file

1. The location of the startup file is defined in the Scilab Environment


Variable SCIHOME. Display its value in the Scilab console and note it
down. On Windows 7, it is
usually C:\Users\<Username>\AppData\Roaming\Scilab\scilab-
<version>. It will be different on Windows XP, but SCIHOME will correctly
tell you what this directory is. On *nix it is usually /home/<user>
2. Name of the startup file is .scilab.ini (Windows) or scilab (*nix, don't forget
the . at the start)

Commands to put in the startup file

1. Your Current Working Directory. For


example cd('C:\Users\Satish\Scilab');
2. Any constants or variables you want to use in every Scilab session
3. Anything else you wish to customze

Task Discussion
Session 4: Creating Matrices and Some Simple Matrix Operations

Objectives
Strength of Scilab, and the primary reason why we are learning how to use it is the
fact that it operates on matrices just as easily as an ordinary calculator works with
scalar data combined with the fact that all matrix operations are built-in and a host
of functions for matrix operations are available. In this session we will learn the
following:

1. Creating matrices.
2. Creating some frequently used standard matrices, such as zero matrices,
identity matrices, diagonal matrices etc.
3. Operations on matrices.

Creating Matrices
Here is how we create a matrix with 2 rows and 3 columns, with the first row
containing the numbers 1, 2, 3 and the second row containing the numbers 4, 5, 6:
-->a = [1, 2, 3; 4, 5, 6] // a 2x3 matrix

a =

1 2 3

4 5 6

-->b = [1 2 3; 4 5 6] // Note, no commas, whitespace is same as comma

b =

1 2 3

4 5 6

-->c = [1 2 3

-->4 5 6] // Same as above. Enter instead of semicolon

-->d = [1 2 3] // Row vector, matrix of size 1x3

-->x = [1; 2; 3] // Column vector, matrix of size 3x1

-->y = [1 2 3]' // Transpose. Row vector becomes column vector


-->z = 100 // Scalar, matrix of size 1x1. Check with whos -name
z

Important Notes

1. In Scilab, all constants are matrices. Even scalars are matrices of size
1x1.
2. Elements in the row of a matrix can be separated by commas, whitespace
or both.
3. Rows of a matrix can be separated semicolon or newline or both.
4. Elements of a matrix must be enclosed within a pair of matching square
brackets.
5. Number of columns in each row must be same. It is an error if you supply
different number of columns in different rows. Thus, number of columns in
subsequent rows must be the same as in the first row.

Screencast
Watch the screencast on YouTube (There is no audio. Read the comments. No
need to type the comments when you try out the commands)
Size of a Matrix
You can enquire and determine the size of a matrix. The function are:

• Function size() returns the size of a matrix as a row vector with two
columns, the first column indicating the number of rows and the second
column indicating the number of columns.
• Function length() returns a scalar, the number of elements in the matrix.

-->a = rand(3, 4); size(a), length(a)


ans =
3. 4.
ans =
12.

Since matrix a has size 3x4, size() returns the row vector [3, 4]
and length() returns the scalar 12.
Creating Frequently Used Standard Matrices
You can quickly create some frequently required standard matrices of the following
types:

1. Matrix with all elements zeros


2. Matrix with all elements ones
3. Identity matrix
4. Matrix with specified values on the main diagonal
5. Matrix with randomly generated numbers as its elements

-->a = zeros(3,4) // Matrix of size 3x4, with all elements zeros

-->b = ones(4, 2) // Matrix of size 4x2, with all element szeros

-->c = eye(3, 3) // Identity matrix of size 3x3

-->d = eye(3, 5) // Identity matrix of size 3x5, a non-square id


entity matrix!

-->x = diag([1 2 3]) // Diagonal matrix of size 3x3, diagonal elemen


ts given in the row matrix [1 2 3]

-->y = diag([1 2 3], 1) // Matrix of size 4x4, matrix [1 2 3] placed


one place above the main diagonal

-->z = diag([1 2 3], -1) // Same as above, but placed one place below
the main diagonal

-->m = rand(3, 5) // Matrix of size 3x5, with random numbers as i


ts elements

Creating an Empty Matrix


An empty matrix is a matrix of size 0x0. Although not very useful in any
calculations, it is possible to create an empty matrix, as follows:
-->x = [ ] // Empty matrix
-->whos -name x // Display size of matrix x

See what happens when you operate on an empty matrix. Try adding, subracting
or multiplying an empty matrix to other non-empty matrices.

Screencast
Watch the screencast of YouTube (There is no audio. Read the comments. No
need to type the comments when you try out the commands)
Matrix Operations
To start with, let us look at the following matrix operations:

1. Matrix addition
2. Matrix subtraction
3. Matrix multiplications
4. Matrix division
5. Matrix transpose
6. Exponentiation
7. Arithmetic operations: sqrt(), abs() etc.
8. Trigonometric operations
9. Logarithmic operations
10. Hyperbolic operations

-->// 3x3 matrix of random numbers between 0 and 1

-->a = rand(3, 3)

-->// 3x3 matrix of random numbers between 0 and 10

-->a = rand(3, 3) * 10

-->// 3x3 matrix of integer random numbers between 0 and 10

-->a = int(rand(3, 3)*10)

-->// b is transpose of a

-->b = a'

-->// c is the matrix sum of a and b

-->c = a + b

-->// d is matrix b subtracted from matrix a

-->d = a - b

-->// x is matrix product of a and b

-->x = a * b

-->// Create b, column vector of size 3x1, integer random numbers


-->b = int(rand(3, 1)*10)

-->// Solve linear equations [A] {x} = {b} for unknowns {x}

-->// written as x = a \ b, [a] in denominator, {b} in numerator

-->x = a \ b

-->// a^2 is same as a * a, matrix multiplication

-->x = a^2

-->// a^3 is same as a * a * a

-->y = a^3

-->// Matrix with elements which are square roots of corresponding el


ements of a

-->z = sqrt(a)

-->// Matrix with elements which are sine values of corresponding ele
ments of a

-->y = sin(a)

Screencast
Watch the screencast on YouTube (There is no audio. Read the comments. No
need to type the comments when you try out the commands)
Elementwise Operations
Some matrix operations, such as addition, subtraction, trigonometric, logarithmic,
hyperbolic, sqrt(), abs() etc. are performed elementwise. But others, such as
multiplication, exponentiation are not. Sometimes, it may be meaningful to perform
these operations elementwise rather as matrix operations. For example, if you
want c = a * b to mean an elementwise operation denoted by cij = aij * bij, j=1 to n,
i=1 to m, then what you want is elementwise multiplication. In Scilab you can tell
Scilab to perform an elementwise multiplication with the operator .*, as follows:
-->c = a .* b // a and b must be of same size

-->y = 1 ./ x // Invert each element of x and store it in. yij = 1 /


xij
In the second statement above, space between the numerator 1 and decimal point
(.) is necessary. 1./x is interpreted as 1.0 / x, which is invalid, unless x is of size
1x1. Similarly, a^2 is a*a, matrix multiplication of a and a. But b = a .* a is an
elementwise operation so that bij = aij * aij, that is bij = (aij)^2.
-->a = int(rand(3,4)*10)

-->b = a.^2

Can you explain what is a .^3? Is a .^ 0.5 valid? If yes, what does it represent?

The operation a .+ b is an error, because matrix addition is already an elementwise


operation.

Screencast
Watch the screencast on YouTube (There is no audio. Read the comments. No
need to type the comments when you try ouy the commands)
Size of a Matrix
Scilab has functions to enquire and find the size of a matrix. The following
functions are available:

1. Function size() returns a row vector, with the columns of the row vector
containing the number of rows and columns.
2. Function length() returns the number of elements in the matrix.

-->a = ones(3, 4); b = ones(1, 5)l c = ones(4,1);


-->size(a), size(b), size(c)
ans =
3. 4.
ans =
1. 5.
ans =
4. 1.
-->length(a), length(b), length(x)
ans =
12.
ans =
5.
ans =
4.
Exercises
What is the output of the following expressions? Can you tell the sizes of the
matrices? Assume zi, wn, wd, A and B in the third statement to be scalars and t to
be a column vector.

• a = rand(3,3) * 100 + 1
• x = [0:%pi / 8: 2 * %pi]; y = sin(x)
• y = exp(-zi * wn * t) .* (A * cos(wd * t) + B * sin(wd *
t))

Task Discussion
Session 5: Ranges, Sub-matrix Extraction and Replacement

Objectives
When you work with matrices, one frequent operation is of extracting a sub-matrix
from an existing matrix and its inverse operation of replacing a sub-matrix of an
existing matrix with a specified matrix. Scilab offers handy operations to perform
these two tasks.To simplify these operations, Scilab uses the concept of the range.
To a beginner, these operation appear to be somewhat confusing but learning
them gives you a powerful technique that you will need often.

These techniques are the same ones that are available in Matlab and in Python. If
you are familiar with one of them, you will find this session pretty simple.
Otherwise, it is time to roll up the sleeves and get down to work.

In this session you will learn the following:

1. Ranges and their use to define sequences


2. Extracting a submatrix from an existing matrix
3. Replacing a submatrix within an existing matrix with different values

Ranges
Range is a sequences of numbers that can be generated using the range operator,
namely, colon(:). You can define a variety of ranges:

1. Ranges incrementing by 1, Requires start and end values. End value


must be greater than the start value. Format: start:end.
2. Ranges incrementing by a value other than 1. Increment can be fraction.
End value must be greater than the start value.
Format: start:increment:end.
3. Ranges decrementing by a specified value. End value must be smaller
than the start value. Format: start:decrement:end.

Let us try out a few examples:


-->1:5 // increment is 1

ans =
1. 2. 3. 4. 5.

-->1:2:10 // increment is 2

qns =

1. 3. 5. 7. 9.

-->1:0.5:4 // increment is 0.5

ans =

1. 1.5 2. 2.5 3. 3.5 4.

-->4:-1:1 // decrement is 1

ans =

4. 3. 2. 1.

-->4:-0.5:2 // decrement is 2. Stop at 2

ans =

4. 3.5 3. 2.5 2.

-->b = 1:5 // Row vector, same as b = [1 2 3 4 5]

Ranges are useful because they can be used to select rows and columns of a
matrix. To select rows 2 to 4 and column 3 to 5 of a matrix a, the expression
is a(2:4, 3:5). Here, the range 2:4 selects rows 2, 3 and 4 and the range 3:5 select
columns 3, 4 and 5. Thus, a contiguous submatrix of size 3x3, starting at element
2,3 and ending at (4, 5) is selected for extraction.
Indexing
An element in a matrix can be addressed by referring to its row and column. First
row and column are numbered 1 (unlike some programming languages such as
C/C++, Java and Python which begin numbering rows and columns with 0).
Thus a(2, 3) refers to the element of matrix a, on the second row and third
column.

If a matrix is a vector (either a row or a column vector), you can refer to one of its
element in one of the following ways:

• As a one dimensioned array: a(2) refers to the element in the second


element of the vector
• As a two dimensioned matrix: a(1, 2) referes to the second element of a
row vector. a(2,1) referes to the second element of a column vector. It is
an error to use a(2, 1) for the second element of a row vector and a(1,2)
for the second element of a column vector.

Even when a matrix is a two dimensioned matrix, Scilab allows you to refer to its
elements as if it were a one dimensioned vector (either a row or a column vector
the way you wish to view it). In such a case, the matrix must be viewed as a vector
with elements of the matrix counted column-wise. Thus the elements of a 3x2
matrix could be mapped to a 1x6 vector as follows:
(1,1) (2,1) (3,1) ((1,2) (2,2) (3,2)
(1) (2) (3) (4) (5) (6)

Viewed this way:

• a(1,1) can be referred to as a(1)


• a(1,2) can be referred to as a(4)

and so on. Therefore:


-->a = [1 2 3; 4 5 6]
a =
1. 2. 3.
4. 5. 6.
-->a(1), a(2), a(3)
ans =
1.
ans =
4.
ans =
2.
-->a(4), a(5), a(6)
ans =
5.
ans =
3.
ans =
6.
Sub-matrix Extraction
As discussed above, it is possible to extract a sub-matrix from an existing matrix
and store it in another variable.

It is important to note that Scilab can extract any rows and columns as specified by
a range. The extracted sub-matrix need not consist of contiguous rows and
columns. Let us try out a few examples to understand this concept:
-->a = int(rand(5, 8)*100); // Create matrix a of size 5x8, containi
ng random numbers

-->b = a(2, 3) // Extract element on row 2 column 3 of


a and store it in b. Scalar

-->b = a(2:4, 3:5) // Extract sub-matrix of size 3x3 from a


and store it in b

-->c = a(1:2:5, 2:2:8) // Extract odd numbered rows and even nu


mbered column of a, and stored in c

// Rows 1, 3, 5 and columns 2, 4, 6, 8 a


re extracted. Size 3x4

-->d = a(5:-2:1, 8:-2:2) // Rows 5, 3, 1 and columns 8, 6, 4, 2 a


re extracted from a and stored in d

-->x = a([1, 4, 5], [2, 7]) // Rows 1, 4, 5 and columns 2, 7 of a ar


e extracted from a and stored in x

-->y = a([5, 1, 2], [7, 6]) // Rows 5, 1, 2 and columns 7, 6 are ext
racted from a and stored in y

As you can see, this logic of selecting rows and columns is quite logical. The row
and column numbers can be a scalar, a range or a vector. Elements on the rows
and columns selected are selected for extraction.

While specifying ranges for row and column selection, you can use the following
conventions:

1. The symbol $ represents the number of the last row/column. Thus, to


specify rows 2 to the last, and columns 3 to the last, you can
specify a(2:$, 3:$). This makes it unnecessary to know the number of last
row or column while selecting them.
2. The range 1:$ essentially means all rows/columns. This can be written
simply as :, without specifying either the start or the end value. Thus a(:,
2:$) means all rows and columns starting from 2nd to the last.
3. Either both start start and end values must be specified, or both
must be left out. Specifying only one of them is an error.

Sub-matrix Replacement
When the sub-matrix specification is applied to a matrix on the right hand side of
an assignment statement, it is an extraction operation. In the same way, it is
possible to replace a sub-matrix of an existing matrix with new values. To achieve
this, sub-matrix specification must be applied to a matrix on the left hand side of an
assignment statement.

To set the element on row 2, column 3 of a to zero, the command is:


-->a(2, 3) = 0

The above operation can be performed on a sub-matrix of a instead of on only one


element of a, as long as the right hand side is a zero matrix of the appropriate size.
Let us try this:
-->a(2:4, 3:5) = zeros(3,3)

The zero matrix on the right side is of size 3x3. The sub-matrix of a selected on the
left side is also of size 3x3. Therefore this is a valid assignment operation and it
replaces the 3x3 sub-matrix of a, on rows 2, 3, 4 and columns 3, 4, 5 with zeros.

You can now try out all possible tricks we performed while illustrating sub-matrix
extraction. As long as you remember the rule that the matrices on either side of the
assignment are of the same size, the operation will succeed.

A hint for the impatient. If you don't want to bother counting the number of rows
and columns to be replaced on the left side in order to specify the correct size for
the matrix on the right side, you can leave it to Scilab to do that for you. Thus, the
following will work:
-->a(2:4, 3:5) = ones() // No need to specify rows and columns to th
e function ones()

-->a(2:4, 3:5) = zeros() // Same as for ones()

-->a(2:4, 3:5) = eye() // ERROR. Doesn't work

Use these tricks at your own risk, some of them don't work as expected. For
example, a(2:4, 3:5) = eye(1,1) works, but results are what you expect.
Concatenating Matrices
You can concatenate any number of compatible matrices into a single matrix. All
the matrices being concatenated must have the same number of rows. Assuming
a, b and c have the same number of rows, the following command concatenates
them into a single matrix d
-->d = [a b c]

Thus, the columns of d are the columns of a, b and c concatenated in that order.
Try out the following command, and guest the output:
-->a = int(rand(4,2)*10), b = int(rand(4,1)*50), c =
int(rand(4,1)*100)
-->d = [c a b]
Task Discussion

Brian Vancil June 4, 2011, 11:49 p.m.


I like the logical indexing like with R:
a=1:100

a(modulo(a,2)==0) // selects the even numbers

Satish Annigeri June 5, 2011, 6:29 a.m.


In Reply To: Brian Vancil June 4, 2011, 11:49 p.m.
Yes, that will work perfectly since modulo(a, 2) returns a matrix of boolean
values, and only those elements of a are displayed where the boolean value is
TRUE. As an example:
-->a = [1:10];
-->modulo(a, 2) // returns remainder of integer division
ans =
1. 0. 1. 0. 1. 0. 1. 0. 1. 0.
-->modulo(a, 2) == 0 // F for odd index elements, T for even
index values
ans =
F T F T F T F T F T
-->a(modulo(a, 2) == 0) // displays elements whose index is T
ans =
2. 4. 6. 8. 10.

This will also work for a matrix (unlike for a vector in the above example), but the
final result returned is a vector, not a matrix. For example, try the commands above
with a = [1 2 3 4; 5 6 7 8].
Session 6: Statistics

Objectives
In this session, we will learn the following:

• Scilab functions to obtain basic statistics of the elements of a matrix

Scilab Functions for Statistics


Scilab provides the following functions for computing simple statistics of matrices:

1. sum() - sum of array elements


2. mean() - mean of array elements
3. median() - median of array elements
4. st_deviation() or stdev() - standard deviation of array elements
5. stdevf() - standard deviation of array elements using frequencies
6. nanstdev() - standard deviatin ignoring NaN (not a number) values

Each of these functions can be used in one of hree ways:

1. To calculate the statistical quantity for all elements of the array. x =


sum(a) computes the sum of all elements of matrix a and assigns it to x.
2. y = sum(a, 'r') or y = sum(a, 1) return a row vector wherein the number in
each column is the sum of the elements of the respective column of
matrix a. Thus, y is a row vector having the same number of columns as
matrix a.
3. z = sum(a, 'c') or z = sum(a, 2) return a column vector wherein the
number in each row is the sum of the elements of the respective row of
matrix a. Thus, z is a column vector having the same number of of rows
as matrix a.

Other functions can be used in the same way as the function sum(). Let us try out
an example:
-->a = [73 24 89 94; 20 24 66 22; 55 22 31 32];
-->sum(a)
ans =
552.
-->sum(a, 'r')
ans =
148. 70. 186. 148.
-->sum(a, 'c')
ans =
280.
132.
140.
-->sum(a, 1)
ans =
148. 70. 186. 148.
-->sum(a, 2)
ans =
280.
132.
140.
Task Discussion
Session 7: Working with Polynomials

Objectives
In this session we will learn the following:

• Defining a polynomial
• Performing operations on polynomials
• Finding roots of a polynomial

Defining a Polynomial
A polynomial in x, of order n can be defined as:
p(x) = a0 + a1 x + a2 x2 + ... + an xn

Such a polynomial has n roots and n+1 coefficients, namely, a0, a1, a2, ...,
an.

Polynomial is a built-in data type in Scilab. A polynomial can be defined in one of


several ways.

Defining a Polynomial in terms of its Roots


If we know the roots of the polynomial we wish to define, then
-->p = poly([2 3], 'x')
p =
2
6 - 5x + x

or, alternately
-->p = poly([2 3], 'x', 'r')

Here we define p as a polynomial in x, having the roots specified in the vector [2


3]. This means p is a quadratic polynomial in x, and therefore will have three
coefficients. Note that the coefficients are arranged in the order coefficient of x^0
(constant, x^1, x^2 and so on.

Defining a Polynomial in terms of its Coefficients


If we know the coefficients of the polynomial, then
-->p1 = poly([6 -5 1], 'x', 'c')
p1 =
2
6 -5x + x

This is the same polynomial we defined above, having the roots [2 3].
Shortcut for p(x) = x
-->p = poly([0 1], 'x', 'c')
p =
x

This can be created in another way.


-->p = poly(0, 'x')

This can be used to define a polynomial, much the same way as we write a
polynomial on paper:
-->x = poly(0, 'x')
-->p = 6 - 5*x + x^2
p =
2
6 -5x + x
-->roots(p)
ans =
2
3
-->coeff(p)
ans =
6 -5 1
Operations on Polynomials
Operations on polynomials include addition, subtraction, multiplication with a
scalar, multiplication with a polynomial, division by a scalar, division by a
polynomial.

Let us try the following:


-->p1 = poly([2 3], 'x'); p2 = poly([6 -5 1], 'x', 'c');
-->p3 = p1 + p2, p4 = p1 - p2
p3 =
2
12 - 10x + 2x
-->p1 - p2
ans =
0
-->2 * p1
ans =
2
12 - 10x + 2x
-->p1 * p2
ans =
2 3 4
36 - 60x + 37x - 10x + x
-->p1 / 2
ans =
2
6 - 2.5x + 0.5x
-->p = p1 / p2
ans =
1
-
1
-->typeof(p)
ans =
rational

Note that dividing a polynomial by another polynomial results in a rational. Here in


this case the numerator and denominator are identical and hence result is 1. If the
polynomials are of different order, the result will contain x.
-->poly([2 3 5], 'x') / poly([4 3], 'x')
ans =
2
10 - 7x + x
-----------
-4 + x

It is an error to attempt polynomial operations on two polynomials of different


variables. For example, if p1 is a polynomial in x and p2 is a polynomial in y,
adding the two polynomials results in an error.
-->poly([2 3], 'x') + poly([2 3], 'y')
!--error 144
Undefined operaion for the given operand

Boolean operaions are also be used


-->p1 == p2 // equal to
ans =
T
-->p1 ~= p2 // not equal to
ans =
F
Coefficients, Roots and Derivatives
Other operations on a polynomials include extracting its coefficients, computing its
roots, determining its derivative.

1. coeff(p) returns a row vector containing the coefficients of the polynomial.


2. roots(p) returns a column vector containing the roots of the polynomial.
3. companion(p) returns the companion matrix (a matrix whose
characteristic equation is the given polynomial) of the polynomial
4. derivat(p) returns a polynomial which is the derivative of p

If c is the companion matrix of the given polynomial, spec(c) are the eigenvalues
of the companion matrix c, which are the same as the roots of the characteristic
equation (which is the given polynomial p).
New Functions used in this Session
poly(), coeff(), roots(), companion(), derivat(), spec()
Task Discussion
Session 8: Plotting Graphs

Objectives
In this session you will learn the following:

1. Plotting 2 dimensional line graphs


2. Annotating graphs with grids, axis labels, graph titles
3. Exporting graphs for inclusion in documents
4. Plotting 3 dimensional surface graphs
5. Plotting multiple graphs on one page (subplot())

Functions for Plotting


In this session, we will learn the following functions:

plot(), plot2d(), xgrid(), xtitle(), legend(), plot3d(), linspace()


Plotting Basics
Scilab is a data plotter, that is, it plots graphs from the data you input. This is in
contrast to function plotting programs (such as gnuplot) which plot graphs of
functions without the user having to first explicitly generate the data required to plot
the graph. Function plotting programs will decide the range of the values of
independent variable and its data interval, generate the data on the fly and plot the
graph.

Let us plot a graph of sin(x) and cos(x) over the range x = 0 to 2 pi. We will first
create vector x, containing the values of the independent variable x. Then we will
create the matrix y, containing the same number of rows as x, with values of sin(x)
in its first column and values of cos(x) in its second column.
-->x = [0:%pi/16:2*%pi]';
-->y = [sin(x), cos(x)];
-->plot(x, y); xgrid(1); xtitle('Harmonic Functions', 'x',
'sin(x) and cos(x)');

This must result in the following graph being plotted:

Let me explain how this was achieved:


1. Using the plot() function, we tell Scilab to look for values of x in the first
variable (namely x) and look for values of y in the second variable
(namely y). The number of rows in x and y must be the same. Since y
contains two columns, Scilab understands that it must plot two lines in the
graph, one each for each column of values.
2. Using xgrid() function, we tell Scilab to plot grids parallel to the x- and y-
axes in black color (argument 1 to the function xgrid()).
3. Using the xtitle() function, we define the title of the graph (first argument),
title for the x-axis (second argument) and title for the y-axis (third
argument).

In the same way, we could define a legend with the legend() function as follows:
-->plot(x, y); xgrid(1); xtitle('Harmonic Functions', 'x',
'sin(x), cos(x)'); legend(['sin(x)', 'cos(x)'], 3)

First argument to legend() is an array of strings containing the legend text and the
second argument specifies the position. Use the online help to learn more about
the legend() function.
Interactive Editing of Plots
When the plot() function finishes plotting the graph, you see a graphic window, with
its own main menu and the graph shown underneath. To interactively modify the
different properties of the graph, click on Edit -> Figure Properties. This
brings up the Figure Editor. It displays a tree diagram showing all the components
of the graph, and you can interactively modify fonts, font sizes, axis labels, grids
etc.

Watch the screncast on YouTube.


Plotting 3D Graphs
While 2D graphs are lines, 3D graphs are surfaces. To plot 3D graphs, we need (x,
y, z) coordinates of points lying on the surface. There are two ways in which 3D
graphs can be plotted in Scilab:

1. By specifying z coordinates of intersection of a grid lying in the x-y plane.


That is, (x, y, z) coordinates of intersction points of a grid in the x-y plane.
The grid spacing along x- and y-axes may or may not be the same.
2. By specifying the coordinates of the four corners of four sided polygons
(or facets).
3D Graphs using Grids
The grid is generated by specifying two vectors giving the coordinates along the x-
and y-axes. The grid is obtained by computing the coordinates of all intersection
points. A third vector specifies the z coordinates of the intersection points of the
grid. Thus, if x is a vector of size mx1, and y is a vector of size 1xn, then z is a
matrix of size mxn. Study the following example:
-->x = [0:%pi/16:2*%pi]'; // Note the transpose. Size is 33x1
-->y = [0:5]; // Size 1x6
-->z = sin(x) * ones(y); // ones(y) has same size as y and
all elements are 1
-->size(x), size(y), size(z)
ans =
33. 1.
ans =
1. 6.
ans =
33. 6.
-->plot3d(x, y, z)
Function plot3d1() is similar to function plot3d(), except that it produces a
colour level plot of the surface, using the same colour for points with same height
(or for points lying within a certain range of height).

3D Graphs using Facets


Function plot3d2() generates surfaces using facets rather than grids. Here, the
arguments to the function, namely, x, y and z are two dimensional matrices. The
surface is composed of four sided polygons, with the x coordinate of the polygon
stored in x(i, j), x(i+1, j), x(i, j+1) and x(i+1, j+1). Similarly, the y and z coordinates
of the polygons are stored in the y and z matrices.
In the following example, we will use the function linspace(s1, s2, n) to
generate n equally spaced values with s1 as the start value and s2 as the end
value. Thus linspace(0, 10, 11) is equivalent to the range 0:10.
Similarly, linspace(0, 10, 21) is the same as the range 0:0.5:10.

-->u = linspace(-%pi/2, %pi/2, 40); size(u)


ans =
1. 40.
-->v = linspace(0, 2*%pi, 20); size(v)
ans =
1. 20.
-->x = cos(u)' * cos(v); size(x) // cos(u)' is 40x1, cos(v)
is 1x20
ans =
40. 20.
-->y = cos(u)' * sin(u);
-->z = sin(u)' * ones(v);
-->plot3d2(x, y, z)
Plotting Multiple Graphs using subplot()
Function subplot() is used to plot multiple graphs within one graphics window.
Thesubplot() command must immediately precede a plotting command in order
to produce a sub-plot. The subplot() function logically divides the graphic
window into an array of rows and columns, and chooses one of the cells as the
output of the subsequent plotting command. For example, subplot(235) divides the
window into two rows and 3 columns (that is 6 cells in all). Cells are counted in
sequence starting from top left proceeding to the right first and then down.
Therefore cell 5 in the above command implies that the output of the next plotting
command will be sent to the cell on row 2, column 2.
-->clf(); subplot(121); plot3d2(x, y, z); subplot(122);
plot3d3(x, y, z)
Exporting Graphs
Graphs can be exported to one of the following formats: PNG, PPM, EMF, EPS,
FIG, PDF and SVG. To export the contents of the graphics window, go to the main
menu of the graphics window and choose File -> Export to (Ctrl+E). This opens a
dialog box where you can choose the filename for the image file and its file type.
The image cn then be imported into a document.
LaTeX Rendering in Graphs
Scilab can display mathematical equations written in LaTeX or MathML languages.
I will demonstrate only the LaTeX capabilities by writing the axis titles of the above
sine and cosine function graphs.
-->x = [0:%pi/16:2*%pi]'; y = [sin(x), cos(x)]; plot(x, y);
xgrid(1);
-->xtitle("Harmonic Functions", "$\theta$", "$\sin (\theta),
\cos (\theta)$")

Note the x- and y-axis labels with the Greek letter theta and the way sin and cos
are rendered.
Task Discussion
Session 9: Scilab Programming Language

Objectives
In this session you will learn the following:

1. Program control structures for looping and branching


2. Boolean operators, expressions and statements

Introduction
During our interaction with Scilab, we have been using the Scilab programming
language even though we have been thinking we are using Scilab commands and
not the programming language. That is because, we have not interactively used
any program flow control structures such as if(), for etc. Nevertheless, we already
know a little bit about Scilab programming language, such as, creating variables,
writing expressions and statements, calling functions. Th eadditional things we
need to learn are:

1. Program flow control structures.


2. Boolean operations, expressions and statements.
3. Writing our own functions and using them within Scilab
4. File input and output

The best thing about an interactive programming environment such as Scilab is


that even program control statements can be tried interactively and results
observed immediately without having to go through the steps of compiling, linking
and executting programs to understand how these work in a programming
language.
Program Flow Control - Loops

The for Loop


Let us display the numbers from 1 to 5 using the for loop:
-->for i = 1:5
-->disp(i)
-->end
1.
2.
3.
4.
5.

Let us display all odd numbers between 1 and 5:


-->for i = 1:2:5
-->disp(i)
-->end
1.
3.
5.

The values of the loop index variable i are the values of the range used to define
loop. Hence the increment can be a fraction, or it can be negative.

The while Loop


Let us calculate the machine epsilon using the while loop:
-->e = 1; k = 0;
-->while 1+(e/2) ~= 1 do
-->e = e / 2; k = k + 1;
-->end
-->e, k
e =
2.200D-16
k =
52.

Starting from e = 1, it takes 52 iterations to arrive at the machine epsilon,


namely, 2.200D-16.

The do in the while loop after the expression 1+(e/2) ~= 1 can be replaced with
then, or alternately, it can also be completely dropped.
Program Flow - Branching and Decision Making

Branching using if-then-elseif-else


The following code segment shows how to use the if-then-elseif-else control
structure:
-->x = int(rand(1) * 100 - 50);
-->if x > 0 then
-->disp('Positive')
-->elseif x == 0 then
-->disp('Zero')
-->else
-->disp('Negative')
-->end

Output of the above statements is one of Positive, Zero or Negative depending on


the value of x. You will also notice that when you type the above statements
interactively, the result will be displayed even before the closing end is typed. This
is due to the short circuiting of boolean expression evaluation - when one of the
conditions being tested is met, there is no need to evaluate the remaining tests.

Branching using select


Branching using select is similar to the switch statement in C/C++. It can compare
the value of a variable to a constant and and if found to be equal, can execute a
set of statements.
-->x = int(rand(1) * 3;
-->select n
-->case 0 then
-->disp('Zero')
-->case 1 then
-->disp('One')
-->case 2 then
-->disp('Two')
-->else
-->disp('Too big')
-->end

Here too boolean short circuiting occurs and as soon as one of the expressions
turns out to be true, the rest are not tested.
Boolean Operations, Expressions and Statements
The list of boolean operators is given below:
== Equal to ~= Not equal to

> Greater than >= Greater than or equal to


< Less than <= Less than or equal to
~ Negation <> Same as ~=
& Elementwise AND | Elementwise OR

Boolean constants are %f or %F representing FALSE and %t and %T representing


TRUE. When these operators are applied to a matrix, the result is a matrix having
the same size as the given matrix with elements either T or F depending on what
the result would be if the operator were applied to that element instead of to the
whole matrix.
-->a = int(rand(3,4)*20; a > 10, bool2s(a > 10)

returns a 3x4 matrix of boolean values. Elements of the result corresponding to an


element in the given matrix a will be TRUE if that element is greater than 10,
otherwise FALSE. Function bool2s(a > 10) is similar to a > 10, except that it returns
a matrix of integers 0 or 1 instead of returning a matrix of TRUE or FALSE values.

Function find(boolean_expr) returns a vector containing indices of those elements


of a given matrix that satisfy the specified logical condition. Using these indices, it
is possible to print the elements at these locations.
-->a = int(rand(3, 4)*100);
-->x = find(a < 20);
-->a(x)

Note that x is a vector, even if a is a matrix. Therefore a(x) is also a vector. Indices
in x treat the matrix a as a vector with the elements indexed column-wise.

A compound logical statement can be constructed as follows:


-->x = find(a < 20 | a > 70); a(x) // logical OR
-->y = find(a > 20 & a < 70); a(y) // logical AND

Function and() returns the logical AND of the elements of a matrix. Function or()
returns the logical OR of a matrix.
-->and(a > 10) // TRUE if all elements of a are greater than
10
-->or(a > 10) // TRUE if at least one element of a is
greater than 10
Task Discussion
Session 10: Script Files and Function Files

Objectives
In this session, you will learn the following:

1. Difference between a script file and a function file


2. Writing a script file
3. Developing a simple function to calculate the length of a line segment

Introduction
Script files are comparable to shell scripts in *nix and batch files in Windows. They
are executable files containing statements that are valid Scilab commands. It is
simply the non-interactive version of the interactive sessions with Scilab that we
are used to up to now. Thus, when you need to type a series of Scilab commands
one after the other, not just once, but a number of times, then the best way to do it
is to put all those Scilab commands in a text file with a .sce extension and ask
Scilab to execute the commands in that file.

On the other hand, a function file is intended to be modular in the sense that it
takes certain input, processes that input and generates certain output. Thus, the
main difference is the thought that goes into:

1. Identifying what the function is expected to do,


2. What input should the function take,
3. What output should the function generate, and
4. What steps (algorithm) and commands are required to process the input
in order to generate the required output

Once a function is properly designed, it can then be treated as a black box, focus
mainly on what input to give and what output to expect and forget the details of
how it is implemented.

Therfeore, the main difference is the way script files and functions exchange data
with Scilab. Whatever input data a script file accesses is taken from Scilab
workspace. Whatever data a script file outputs is put into Scilab workspace. The
semantics of input data, local variables being visible only within the function and
output variables being handed to the parent function is not applicable to a script
file.
Writing a Script File
The rules for writing a script file are as follows:

1. Script file must contain only valid Scilab statements,


2. The first word in the script file must not be the keyword function,
3. Script file must be text file (typically with the extension .sce)

To execute a script file, one of the following methods can be used:

1. From the main menu, choose File -> Execute. This opens a dialog box.
Pick the script file and press OK to execute the script file
2. Use the command exec(). To execute a script file test.sce, located in the
current working directory, the command is
-->exec('test.sce')
Knowing about current working directory (Session 3) is important.
3. From the main menu choose File -> Open. This opens a dialog box. Pick
the script file and press OK to open the script file in SciNotes, the built-in
code editor. From the main menu of SciNotes, choose Execute -> ... file
with echo or Execute -> ... file with no echo.

Remember that statements in a script file are executed by Scilab as if they were
typed interactively at the Scilab prompt.

Let us write a script file to calculate the length of a line segment connecting the
points P1 with coordiantes (x1, y1, z1) and P2 with coordinates (x2, y2, z2). Start
Scilab, from the main menu choose Applications -> SciNotes. This will open the
SciNotes source code editor. In a new file, type the following Scilab statements:
p1 = [0, 0, 0];
p2 = [3, 4, 5];
delta = p2 - p1
L = sqrt(sum(delta.^2))

Save this file as len1.sce in a different directory of your choice. Take care to note
the filename and directory in order to access this file later. Then execute it from
inside SciNotes from the main menu Execute -> ... file with echo. The lines from
the file will be executed and you will see the results of these statements, anmely:
-->p1 = [0, 0, 0]
p1 =
0. 0. 0.
-->p2 = [3, 4, 5]
p2 =
3. 4. 5.
delta =
3. 4. 5.
L =
7.0710678
Developing a Function
We will develop a function based on the above calculation. The specifications of
the function are:

1. Purpose: Function calculates the length of a line segment joining two


points in 3D space with specified coordinates.
2. Name of the function: len. Note: There is a function named length()
already in use by Scilab.
3. Input: Coordinates of the two end points. Coordinates of each point are in
the form of 1x3 row vector.
4. Output: Length of the line segment

The skeleton of a typical Scilab function is as follows:


function [output1, output2, ...] = function_name(input1,
input2, ...)
statement_1
statement_2
...
statement_n
endfunction

Note the following:

1. Scilab keywords: function and endfunction are Scilab keywords


indicating the start and end of a function
2. function_name is the name of the function chosen by the programmer
3. Input arguments are listed after the function name, within parentheses
and separated by commas. A function can have zero or more number of
input arguments
4. Output arguments are listed to the left of the assignment operator, within
square brackets and separated by commas. A function can have one or
more output arguments.
5. If a variable appears both in the list of input as well as output arguments,
it means that its value can be used by the function as well as its altered
value is returned to the parent function
6. A function can have any numbr of statements within its body

Here is our function to calculate the length of the line segment in 3D space:
function [L] = len(p1, p2)
delta = p2 - p1;
L = sqrt(sum(delta .^2))
endfunction

Save this in a file (note down its name and directory) and load the function into
Scilab workspace (Execute -> ... file with echo). Check that it is loaded into Scilab
workspace using the whos -type function command (See Session 3 for details).
Once the function is loaded into Scilab workspace, it is available for use, in the
same way as Scilab functions are available for use. The difference is, it may be
necessary to explicitly load it into Scilab workspace before it is available for use.
This is how you could use the function:
-->L1 = len([0 0 0], [3 4 5])
L1 =
7.0710678
-->p1 = [0 0 0]; p2 = [3 4 5]; L2 = len(p1, p2)
L2 =
7.0710678
Task Discussion
Task Navigation
Session 11: Writing Scilab Functions

Objectives
In this session you will learn the following:

1. Writing inline functions


2. Number of input and output arguments and parameters
3. Setting default values to input arguments

Introduction
In session 10, we saw the basic skeleton for a Scilab function and a simple
example to illustrate how to develop and use a function. Here we will take a closer
look at counting input and output arguments. We will also see how do define an
inline function.
Inline Functions
An inline function is a short function that can be defined without having to use the
function skeleton discussed in Session 10. This is useful only when the body of the
function is short (in case the body of the function is long, it could be first stored in a
string and then used to define the inline function). We will again use the same
function used in Session 10 as an example. The syntax for defining an inline
function is:
deff(func_interface_str, func_body_str)

where func_interface_str is a string containing the interface of the function


and func_body_str is a string containing the body of the function. The function to
find the length of a line segment in 3D space can therefore be written as:
-->deff('[L] = len(p1, p2)', 'L = sqrt(sum((p2 - p1).^2))');

Alternately, the function could also be defined as:


-->s1 = '[L] = len(p1, p2)';
-->s2 = 'L = sqrt(sum((p2 - p1).^2))'
-->deff(s1, s2)
-->len([0 0 0], [3 4 5])
ans =
7.0710678

This could be advantageous when the body of the function contains a very long
statement and is difficult to fit it on a single line. If you want to define an inline
function with multiple lines, use an array of strings as the second input argument.
The above function could be split into multiple lines as shown below:
-->s1 = '[L] = len(p1, p2)';
-->s2 = ['delta = p2 - p1;', 'ss = sum(delta.^2);', 'L =
sqrt(ss);'];
-->deff(s1, s2)
-->len([0 0 0], [3 4 5])
ans =
7.0710678
Number of Arguments
The number of input and output parameters are defined when the function is
defined. It is quite easy to understand what happens when you supply the same
number of input and output arguments during a function call. However, it is
possible to call a function without the correct number of matching arguments.

With reference to function definitions and their use during a function call,
parameters appear in function definition and arguments appear in function calls
(See this article section on Wikipedia).

Here are some rules you must remember about input arguments and input
parameters:

1. Number of input arguments can be equal to or less than the number of


parameters.
2. Providing more input arguments than the number of input parameters is
an error.
3. If you provide fewer arguments than the number of parameters, it is an
error to use an argument that is not provided. As an example, if the
number of input parameters is 3 and number of input arguments is two,
attempting to use the third parameter within the body of the function
results in an error. If you can check how many arguments have been
supplied at run time and avoid using the ones not provided does not result
in an error.
4. It is possible to determine the number of arguments to a function at run
time, and assign default values to those parameters which do not have
corresponding arguments. This is akin to default values assigned to
parameters in languages such as C++, but this has to be done explicitly
by the programmer and does not happen automatically.
5. Input arguments may be either variables or constants.

Here are some rules you must remember about output arguments and output
parameters:

1. Number of output arguments can be equal to or less than the number of


output parameters.
2. It is an error to provide more output arguments than the number of output
parameters.
3. If you provide fewer arguments than the number of output parameters,
values of the output parameters without a corresponding output argument
are lost and not available to the parent function.
4. If no output arguments are provided, the value of the first output
parameter is assigned to the built-in variable ans, values of other output
parameters are lost.
5. Output arguments must be variables, they cannot be replaced by
constants. In C language parlance, they must be an lvalue (capable of
storing a value in them).

Scilab provides the function argn() to count the number of unput and output
arguments at run time. Let us use the following function to show how this can be
used and also illustrate the above points:
function [a, b] = testarg(x, y, z)
[out, inp] = argn(0);
mprintf("Output: %d, Input = %d\n") // print function
similar to printf in C
if inp < 3 then, z = 20, end
if inp < 2 then, y = 10, end
if inp < 1 then, x = 5, end

disp([ x, y, z]);
a = x + y; b = 2 * z;
endfunction
Save this function in a file and load it into Scilab workspace. Let us call this
function in the following different ways. Note what we have done within the body of
the function:

1. We determine the actual number of output and input arguments provided


to the function at run time using the function call [out, inp] =
argn(0).
2. We print out the number of output and input arguments provided to the
function at run time.
3. We check to see if the number of input arguments is less than 3 (that is,
either 1 or 2; which implies that argument corresponding to parameter z is
not provided). If so, we assign an arbitrary default value to z.
4. We check to see if the number of input arguments is less than 2 (that is,
1; which implies that argument corresponding to parameter y is not
provided). If so, we assign an arbitrary default value to y.
5. We repeat this operation for parameter x.
6. We display the values of the input arguments x, y and z.
7. We compute the values of the two output arguments using the input
values (the relationships between a and b and x, y and z are arbitrary,
only for the purpose of explaining this concept of number of input and
output arguments and parameters).

// all input and output arguments provided exactly as


required
-->[a, b] = testarg(1, 2, 3)
Output: 2, Input: 3
1. 2. 3.
b =
6.
a =
3.
-->[a, b] = testarg(1, 2) // 3rd input argument not provided
Output: 2, Input: 2
1. 2. 20.
b =
40.
a =
3.
-->[a, b] = testarg(1) // 2nd and 3rd input arguments not
provided
Output: 2, Input: 1
1. 10. 20.
b =
40.
a =
11.
-->[a, b] = testarg() // No input arguments provided
Output: 2, Input: 0
5. 10. 20.
b =
40.
a =
15.
-->[a, b] = testarg(1, 2, 3, 4) // more input arguments than
parameters
!-- error 58
Wrong number of input arguments:
Arguments are:
x y z

Now, let us test the output arguments:


-->[a] = testarg(1, 2, 3) // 2ns output argument not provided
Output: 1, Input: 3
1. 2. 3.
a =
3.
-->testarg(1, 2, 3) // No output arguments
Output: 0, Input: 3
1. 2. 3.
ans =
3.
-->[a, b, c] = testarg(1, 2, 3) // Extra output argument
Output: 3, Input: 3
1. 2. 3.
!-- error 4
Undefined variable: c
Task Discussion
Session 12: File operations

Objectives
In this session we will learn the following:

1. Writing formatted output to Scilab console


2. Reading data from files into Scilab variables
3. Writing formatted output to a file

Introduction
Scilab file operations are similar to those in C programming language. If you are
familiar with file operations in C, you will find it easy to perform file operations in
Scilab. But this session does not assume you know C.

For both input and output, you will find a set of three similar functions - output to
standard output (or input from standard input), output to (or input from) a file and
output to (or input from) a string.

To write to (or read from) a file, it is necessary to first open the file for writing (or
reading), perform the write (or read) operations and finally close the file.
Functions Used
mopen(), mprintf(), mfprintf(), msprintf(), mfscanf(), msscanf()
Output Functions

Output to Standard Output (Scilab Console) - mprintf()


Let us first write scalar values first and then see how to write matrices.
-->mprintf("%5d, %12.3f\n", 120, 1234.55)
120, 1234.55

Notice what happened:

1. To the function mprintf(), we provided three arguments. First, a string


containing formatting specifications ("%5d, %12.3f\n"). Second is an
integer (120). Third is a real number (1234.55)
2. The formatting specification contains two format placeholders, namely,
%5d and %12.3f. Format placeholders begin with the %. Rest of the
formatting specification string are output as they are.
3. %5d corresponds to the second argument to mprintf(), namely 120. It
outputs 120 as an integer (%d), formatting it is a width of 5 places (%5d)
4. %12.3f can be understood as follows - 12 is the width, 3 is the precision
(number of decimal places) and f corresponds to a float (real number).
5. If there are two placeholders in the formatting specification string, it must
be followed by two values with the matching data type as in the formatting
specification.

To print out values of a matrix, the format specification string must be able to print
one full row of the matrix. This specification will be used for each row of the matrix
until all rows are printed. It is an error to provide too few or too many placeholders
in the format specification string than the number of columns being printed. Let us
see an example:
-->a = [1 2 3 4; 5 6 7 8];
-->mprintf("%5.2f,%5.2f,%5.2f,%5.2f\n", a)
1.00, 2.00, 3.00, 4.00
5.00, 6.00, 7.00, 8.00
-->b = [10 11; 20 21; 30 31]; // 3x2 matrix
-->mprintf("%5.2f,%5.2f,%5.2f,%5.2f\t%8.3f,%8.3f\n", a, b)
1.00, 2.00, 3.00, 4.00 10.000, 11.000
5.00, 6.00, 7.00, 8.00 20.000, 21.000

Note that only two rows of matrix b are printed and not all the three. When printing
values from more than one matrix, only that many rows are printed as the minimum
number of rows in the matrices being printed. In the abov case, a is of size 2x4 and
b is of size 3x2. Hence only 2 rows are printed from each matrix. The formatting
specification string must contain enough placeholders required to print all the
columns of all matrices being printed, which is 4 + 2 = 6 in the above case.

Output to a String - msprintf()


Function msprintf() is similar to mprintf(), except that the output is sent to a string
variable (for storage and subsequent output) instead of to the standard output. The
above output statements could be rewritten for output to a string as follows:
-->n = 20; s1 = msprintf("Number of items = %d\n", n);
-->disp(s1)
Number of items = 20
a = [1 2 3 4; 5 6 7 8];
-->s2 = msprintf("%5.2f,%5.2f,%5.2f,%5.2f\n", a)
-->disp(s2)
! 1.00, 2.00, 3.00, 4.00 !
! !
! 5.00, 6.00, 7.00, 8.00 !

Output to a File - mfprintf()


Function mfprintf() send the output to a file. Its use is similar to mprintf() and
msprintf(), except that:

1. The file to which output is to be sent must first be opened using


the mopen() function. If this function call is successful, it returns a file
descriptor which must be used in all subsequent write operations to the
file. It requires two input arguments:
1. A string containing the name of the file to be opened (test.dat in the
example below. It is a good idea to check your current working
directory).
2. A string specifying the type of file operation to be performed on the file
after opening (other possibility is "r" for reading).
2. The mfprintf() takes one argument more than mprintf() and msprintf().
The first argument must be the file descriptor obtained with
the mfopen() function.
3. When all output to the file are complete, the file must be closed
using mclose() function.

-->n = 20; a = [1 2 3 4; 5 6 7 8];


-->fd = mopen("test.dat", "w"); // Creates a new file or
opens an existing file and truncates to zero length
-->mfprintf(fd, "Number of items = %d\n", n)
-->mfprintf(fd, %5.2f,%5.2f,%5.2f,%5.2f\n", a)
-->mclose(fd)

Note the current working directory, then search and open the file test.dat in an
editor. It will containg the following lines:
Number of items = 20
1.00, 2.00, 3.00, 4.00
5.00, 6.00, 7.00, 8.00
Input Functions
Input functions parse and convert text input into data as prescribed in the format
specification string, the opposite of what the output functions do (which is
converting data into text output).

Input from Standard Input - mscanf()


The input functions are used as follows:
-->[n, a, b, c] = mscanf("%d%f%f)
5 12.5 -2.5
c =
-2.5
b =
12.5
a =
5

Number of placeholders in the format specification string indicate the number of


values expected to be input. The first output argument n on the left hand side of
the function mscanf() is the number of values read. It is -1 if values input are fewer
than the number of placeholders in the format specification string.

The above example is what is called the multiple left hand side (LHS) syntax. This
is to be used when you want to read in multiple values with one mscanf() function.
If you want to read in only one value, the syntax for single LHS is simpler:
-->x = mscanf("%f")
10.5
x =
10.5

To read in multiple lines (that is matrices with a known number of rows), the
function call for a single LHS value is as follows:
-->x = mscanf(2, "%f %f %f")
-->1.1 1.2 1.3
-->2.1 2.2 2.3
x =
1.1 1.2 1.3
2.1 2.2 2.3

Reading multiple lines with multiple LHS is possible if each variable has only one
column. Reading multiple values on the LHS, each with multiple columns is not
possible. Here is how we read values into two variables, namely, a and b, each
having a single column and 3 rows:
-->[n, a, b] = mscanf(3, "%f %f")
-->1.1 1.2
-->2.1 2.2
-->3.1 3.2
b =
1.2
2.2
3.2
a =
1.1
2.1
3.1
n =
2

Using msscanf() and mfscanf() proceed along similar lines.

Input from a String - msscanf()


Function msscanf() reads the input from a string rather than the standard input
(as mscanf() does). The input arguments for msscanf() are:

1. First input argument is the number of lines to be read for each LHS, but is
optional.
2. Second input argument is the string from which input is to be read.
3. Third input argument is the format specification string

-->[n, a, b, c] = msscanf('5 12.5 -2.5', "%d %f %f")


c =
-2.5
b =
12.5
a =
5
// Initialize the string containing input data
-->s = ['1.1 1.2 1.3'; '2.1 2.2 2.3'];
// Single LHS of size 2x3
-->x = msscanf(2, s, "%f %f %f")
x =
1.1 1.2 1.3
2.1 2.2 2.3

Input from a File - mfscanf()


Operations are:

1. Open the file for reading


2. read from file and convert to data as specified by the format specification
string
3. Close the file

-->//Prepare some sample data for writing


-->x = [0:%pi/16:%pi]'; y = sin(x);
-->// Write data to a file for subsequent reading
-->fd = mopen("sine.dat", "w")
fd =
1
-->mfprintf(fd, "%f %f\n", x, y)
-->mclose(fd)
-->// Open the file sine.dat for reading
-->fd = mopen("sine.dat", "r")
fd =
1
-->// Clear data before reading
-->clear x y
-->[n, x, y] = mfscanf(-1, fd, "%f %f");
-->mclose(fd)

To read until end of file, the number of lines to be read is set to -1.
Summary
1. To write to (or read from) a file, the file must first be opened in the write
(or read) mode. File must be closed after all write (or read) operations are
complete. There is no need for a open or close function to write to (or
read from) the standard input or a string.
2. For writing:
1.
Any number of variables can be written out from one mprintf(),
msprintf() or mfprintf() function call.
2. The format specification string must be sufficient to print one full line of
all the variables being written.
3. There is no need to specify the number of rows to be written. The
number of lines written is the smallest of the number of lines amongst
the variables being written.
3. For reading:
1. One or more variables can be read from one mscanf(), msscanf() or
mfscanf() function call. When reading multiple variables from a single
function call, the first output argument is the number of variables read.
2. If the number of input variables is fewer than the number of output
variables specified on the LHS, variables without input values are set
to null matrices.
3. When reading variables, the number of lines to be read must be
specified as the first input argument. If the first input argument is not
an integer, it is assumed that one line is to be read.

Task Discussion
Session 13: Reading Microsoft Excel Files

Objective
In this session you will learn the following:

1. Reading data from Microsoft files

Introduction
Scilab can read numbers and text stored in Microsoft Excel files. As of Scilab
version 5.3.2, only Microsoft Excel 2003 or older files can be read. Microsoft 2007
and Microsoft 2010 files cannot be read (If you have data in the newer versions of
Microsoft Excel, you can choose File ->Save as and choose an older version to be
able to read from Scilab). Since OpenOffice.org Calc and a number of other Office
applications can write Excel files, this discussion is applicable not just to Microsoft
Windows and Microsoft Excel but a variety of operating systems and office
spreadsheet applications.

Importing dat afrom a Microsoft Excel file into Scilab variables simplifies data input
and makes it possible to apply more sophisticated processing than what can be
done in Microsoft Excel.
Functions Used
xls_open(), xls_read(), readxls(), read_csv(), write_csv()
Reading Excel Files - xls_open() and xls_read()
To demostrate the use of these functions, let us first create a Microsoft Excel file
with the following data and save it Microsoft Excel 97-2003 format (.xls extension).
The complete operation involves the following steps:

1. Open the Microsoft Excel file with the xls_open() function.


2. Read the data from the file using xls_read() or readxls() function.
3. Close the file with the mclose() function.

The syntax of xls_open() is as follows:


[fd, sst, sh_names, sh_pos] = xls_open(filename)

Function xls_open() takes one input argument:

1. A string with the file name (including the full path if needed). It is a good
idea to check the current working directory and change it to the directory
where the file to be read is located before commencing with the read
operation.

Function xls_open() requires the following output arguments:

1. fd - File descriptor of the file opened for reading. The file must exist,
otherwise the function returns an error.
2. sst - A vector of all character strings in the Excel sheets
3. sh_names - A vector of strings containing the names of the sheets in the
Excel file
4. sh_pos - A vector of numbers containing the beginning of different sheets
within the Excel file
-->[fd, sst, sh_names, sh_pos] = xls_open("test.xls");
-->fd
fd =
1
-->sst
sst =
!One Two Three !
-->sh_names
sh_names =
!Sheet1 Sheet2 Shet3 !
-->sh_pos
sh_pos =
11847 12441 12831
-->mclose(fd)

Match the output with the contents of the file and you will see that the string
content of the Excel file and the sheet names match.

We can now read the data from the file, both numeric as well as text data.
-->[numeric, text] = xls_read(fd, sh_pos(1))
text =
0. 0. 0. 1.
0. 0. 0. 2.
0. 0. 0. 3.
numeric =
1. 2. 3. NaN
4. 5. 6. NaN
7. 8. 9. NaN
-->disp(text(1,4)) // Display text in cell (1,4) of sheet 1
One

This function takes two input arguments:

1. File descriptor to the the file obtained from the xls_open() function call to
specify the file from which data is to be read.
2. Sheet position of the sheet from which data is to be read. To read data
from the first sheet, use sh_pos(1), 1 being the number of the sheet to
read the data from.

Function xls_read() returns two output values:


1. First matrix numeric contains all the numeric values in the sheet, with
cells containing non-numeric data marked as NaN (Not a number)
2. Second matrix text contains index to the character data stored in the
variable sst returned by xls_open(), with cells containing numeric data
filled with zeros.

Reading Excel Files - readxls()


Function readxls() can accomplish the same task that we just completed using two
functions xls_open() and xls_read(). It is simpler to use and more direct. Function
readxls() takes one input argument, the name of the Excel file. It returns an mlist of
type xls, containing one field named sheets. Data in an individual sheet can then
be read from its fields, namely, value and text. Here is the procedure to read Excel
files using readxls().
-->sheets = readxls("test.xls");
-->typeof(sheets)
ans =
xls
-->s1 = sheets(1);
-->s1.value()
ans =
1. 2. 3. NaN
4. 5. 6. NaN
7. 8. 9. NaN
-->s1.text()
ans =
! One !
! Two !
! Three !
Reading and Writing CSV Files
While xls_read() and readxls() functions enable Scilab to import data from Excel
files, there are no files to export Scilab data to Excel format. However, Scilab has a
function wite_csv()to export Scilab data as comma separated values (CSV) which
can be imported into Excel. Thus Scilab data can be read into Excel indirectly. To
test this, let us open the previous Excel file and save it as CSV file with the
name test.csv.
Following example demonstrates how to read and write CSV files:
-->x = read_csv("test.csv")
x =
!1 2 3 "One" !
!4 5 6 "Two" !
!7 8 9 "Three" !
-->y = [11 12 13; 21 22 23; 31 32 33];
-->write_csv(y, "test2.csv", ",")

Function write_csv() separates values in a row by horizontal tab (ASCII 9 or \t)


and rows by newline (ASCII 10 or \n) by default. To separate values on a line by
commas, supply the third input argument ",". A CSV file is a text file and can be
opened in any text editor and examined. It can also be imported into Excel. You
may need to specify separator as comma in the import dialog box while importing
into Excel.
Task Discussion
Session 14: Data Structures

Objectives
In this session you will learn the following:

1. User defined data structures in Scilab


2. Creating and using struct, cell, list, tlist and mlist

Function Used
struct(), fieldnames(), list(), lstcat(), tlist(), definedfields(), mlist(), cell()
Introduction
User defined data structures offer the programmer the facility to tailor data suited to
represent and program solutions to specific problems. Most data structures are an
agglomeration of basic data types and previously defined user defined data types.
Scilab Data Types
Data types available in Scilab can be listed through the online help on type() and
typeof(). The data types available in Scilab are:
Data Type Object Type Description
1 constant real or complex constant matrix
2 polynomial polynomial matrix
4 boolean boolean matrix
5 sparse sparse matrix
6 boolean sparse sparse boolean matrix
8 int8, int16 or int32 matrix of integers stored in 1, 2 or 4 bytes
9 handle matrix of graphic handles
10 string matrix of character strings
11 un-compiled function (Scilab code)
13 function compiled function (Scilab code)
14 library function library
15 list list
16 tlist typed list (tlist)
17 st or mlist structure or matrix oriented typed list (mlist)
128 pointer pointer
129 size implicit size implicit polynomial used for indexing
130 fptr Scilab intrinsic (C or Fortran code)

The following functions are used to determine data types:

1. Function type(x) returns the type of a Scilab variable x.


2. Function typeof(x) returns a string indicating the type of Scilab object x.

Data Structure - struct


struct is a user defined data structure. Programmer can define fields within the
structure and each field can be any valid Scilab data type. Each field can thus
contain any valid Scilab data and data in any field can be accessed using the dot
convention, namely, object.fieldaccesses field from object. Let us see an
example:
-->s = struct('name', 'John Doe', 'courses', ['MA102',
'HS108', 'CV102'], 'marks', [85, 92, 79]);
-->type(s) // enquire data type
ans =
17.
-->typeof(s) // enquire object type
ans =
st
-->fieldnames(s) // list field names
ans =
!name !
!courses !
!marks !
-->s // display data
name: "John Doe"
courses: ["MA102", "HS108", "CV102"]
marks: [85, 92, 79]
-->s.name // display field "name" of object "s"
ans =
John Doe
-->s.courses // display field "course" of object "s"
ans =
!MA102 HS108 CV102 !
-->s.marks // display field "marks" of object "s"
ans =
85. 92. 79.

This is what happened:

1. We created a struct object with the name s using the struct() function.
While creating this object, we defined the following fieldnames and
assigned them initial values:
1.
name - assigned the value "John Doe"
2. courses - assigned a vector of string elements
3. marks - assigned a vector of numerical elements
2. We enquired the type of the object using type() and typeof() functions.
3. We displayed the field names in the object s using function fieldnames()
4. We displayed the data contained in object s
5. We displayed the individual fields in the object s using
the object.fieldname syntax

The exact same result could also be achieved in a simpler and direct manner with
the following statements:
-->s.name = "John Doe";
-->s.courses = ["MA102", "HS108", "CV102"];
-->s.marks = [85, 92, 71];

In fact, a new field could be added any time with equal ease:
-->s.total = sum(s.marks)
s =
name: "John Doe"
courses: ["MA102", "HS108", "CV102"]
marks: [85, 92, 71]
total: 248

Being a weakly type language, Scilab does not require that variables be declared
before being used. Thususer defined types can be constructed and altered
dynamically. Each field can contain any valid Scilab data type.
Data Structure - list
A list is similar to a struct, but uses indexing to access its components instead of
field names. In addition, operations such as insert/append new nodes, delete
existing nodes is possible. Let us use a list to represent the same information used
in the struct example above:
-->l = list("John Doe", ["MA102", "HS108", "CV102"], [85, 92,
71])
l =
l(1)
John Doe
l(2)
["MA102", "HS108", "CV102"]
l(3)
85. 92. 71.
-->type(l)
ans =
15.
-->typeof(l)
ans =
list

To insert a new node after the last node, do the following:


-->l($+1) = sum(l(3));
-->l(4)
ans =
248.

To insert a node before the first node use l(0). To insert a new node at position i,
use l(i). You can concatenate lists with the function lstcat().
Data Structures - tlist
A tlist is a typed list. It has characteristics that are a combination of a struct and
a list. Like a struct, it uses field names, but the fields can also be accessed using
indexing. Its data type is 16 and its object type is user definable. Like a list, nodes
can be inserted and appended. Let us create a tlist to represent the same
information above, and let us choose to call this data type student.
-->t = tlist(["student", "name", "courses", "marks'], "John
Doe", ["MAT102", "HS108", "CV102"]);
-->type(t)
ans =
16.
-->typeof(t)
ans =
student
-->fieldnames(t)
ans =
!name !
!courses !
!marks !
-->definedfields(t)
ans =
1. 2. 3.
-->t.name
ans =
John Doe
-->t.courses
ans =
-->t(1)
ans =
!student name courses marks !
-->t(2)
ans =
John Doe
-->t(3)
ans =
!MA102 HS108 CV102 !
-->t(4)

From the above, we can understand the following:

1. Data type of tlist is 16. Object type of tlist must be defined by user. If the
first input argument to tlist() is a string, it is the object type of the tlist. If
the first input argument to tlist() is a vector of strings, the fist element of
the vector is the object type and the rest represent field names of the
object.
2. Field names of a tlist can also referred to by their index. Thus t(2) is the
same as t.name, t(3) is the same as t.courses and t(4) is the same
as t.marks.
3. Values may be assigned to the various fields at the time of creating the
object or later. Fields which have been assigned values can be listed with
the function definedfields(). It lists the indices of the fields, not their field
names. t(1) is always defined because object type must be defined at the
time of creating the tlist object.
4. Fieldnames can be defined in advance or inserted later. Values can be
assigned at the time of creating the object or assigned later.

To assign values to t.marks, do the following:


-->t.marks = [85 92 71];

To create a new field total and assign it a value, do the following:


-->t(1) = [t(1), 'total'];
-->t.total = sum(t.marks)
ans =
248.

One advantage of a tlist over a list is that it is possible to overload some of its
default functions, such as the display function disp(). Here we overload the disp
function of the tlist with object type student:
-->// Display using default disp()
-->disp(t)
(1)
!student name courses marks !
(2)
John Doe
(3)
!MA102 HS108 CV102 !
(4)
85. 92. 71.
-->
function %student_p(mytlist)
--> f = fieldnames(mytlist);
--> [m, n] = size(f);
--> mprintf("tlist type: %s\n", typeof(mytlist));
--> for i = 1:m
--> mprintf("%7s: %s\n", f(i), sci2exp(mytlist(f(i))});
--> end
-->endfunction
-->
-->// Display using overloaded disp()
-->disp(t)
tlist type: student
name: John Doe
courses: ["MA102", "HS108", "CV102"]
marks: [85, 92, 71]

Function sci2exp() converts an expression to a string so that it can be output using


the %s format specifier. For details about overloading functions, see online help:
-->help overloading
Data Structure - cell
A cell is an array of matrices. That is, like a matrix, it has elements arranged as
rows and columns. Individual elements of a cell can be addressed in the same way
as we address elements of a matrix, by referring to their row and column position
within the matrix. Each element of a cell can be any valid Scilab data, including
string, polynomial, or even another matrix. But when assigning values to an
element of a cell, the syntax must use cell(index).entries = value, as
shown in the example below:
-->b = cell(3, 1) // Create an empty cell of size 3x1
b =
!{} !
!{} !
!{} !
-->b(1).entries = [1:3]; b(2).entries = 'Scilab';
b(3).entries = poly(1:3, 's')
b =
![1, 2, 3] !
!"Scilab" !
!-6+11*s-6*s^2+s^3 !
-->x = cell(3, 2); x(:,1) = b
![1, 2, 3] {} !
!"Scilab" {} !
!-6+11*s-6*s^2+s^3 {} !
-->// Element extraction
-->x(1, 1) // return value is a cell
ans =
[1, 2, 3]
-->x(1, 1).entries // return value is a matrix
1. 2. 3.
-->// Cell dimensions
-->b.dims // Dimensions of the cell, as int32
ans =
3 1
-->size(b) // Size of the cell, as a double
ans =
3. 1.

Task Discussion
Problem Definitions for Scilab Applications

Objectives
The objective of this session is to solicit from the participants, simple
problems from their respective fields of interest, that are well suited for solving
using Scilab. The contributions may consist of the following:

1. A brief and concise problem statement


2. Some concepts, theory and mathematics required to solve the problem
3. Scilab solution in the form of scripts, functions, numerical examples,
solutions from known theory and comparison of results obtained from
Scilab with those obtained from theory

Sample Problems from Structural Engineering


You are invited to add ascomments to this post, the brief problem statements.
Explaining the theory may involve more effort, in which case you can write it up in a
document, upload it to the web (Google Docs, your blog etc.) and provide the link
in the comment. You can do the same with the solution too.

To get you started, I will list a few problems from structural engineering:

1. Determine the principal stresses and principal planes in a three


dimensional state of stress (Theory of elasticity).
2. Develop a function to compute the least square polynomial fit for a set of
recorded data, similar to the polyfit() function in Matlab. Function must
return the coefficients of the polynomial of the specified degree.
3. Determine the free vibration results (natural frequencies and
corresponding mode shapes) of a multi-degree of freedom spring-mass
system. Frequencies must be arranged in increasing order and columns
of mode shape matrix must be rearranged depending on how the
frequencies are sorted.
4. Analysis of skeletal structures using truss and beam elements by the
direct stiffness matrix method of structural analysis
5. Analysis of continua by the Finite Element Method (I agree the problem is
too big, but can you not make a beginning using the simplest elements?).
6. Optimization of skeletal steel structures (such as trusses, domes, roof
grids) designed as per the building code of your country.

Note that the above are not precise problem definitions and do not include theory,
solution and code. The last few problems will involve considerable effort even for
very simple features (as compared to existing commercial software tools).
Task Discussion

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy