Scilab Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Programming using SCILAB

Unit – I
Outline Views
 Overview of Scilab
 How to get started with Scilab
 Getting help from Scilab
 demonstrations and macros
 The Console – The Editor
 Batch Processing
 Creating Real Variables
 Elementary mathematical functions – Booleans
 Complex Numbers - Integrers
 Floating Points - Strings - Dynamic Variables
Overview of Scilab
•Scilab is a scientific software package for numerical computations providing a
powerful open computing environment for engineering and scientific applications.

•Developed since 1990 by researchers from INRIA (French National Institute for
Research in Computer Science and Control) and ENPC (National School of
Bridges and Roads), it is now maintained and developed by Scilab Consortium
since its creation in May 2003 and integrated into Digiteo Foundation in July
2008.

•The current version is 6.0.2 (February 2019).

•Since 1994 it is distributed freely along with source code through the Internet
and is currently being used in educational and industrial environments around the
world. From version 5 it is released under the GPL compatible CeCILL license.
Cont…
•Scilab includes hundreds of mathematical functions with the possibility to add

interactively functions from various languages (C, Fortran...). It has sophisticated

data structures (including lists, polynomials, rational functions, linear systems...),

an interpreter and a high level programming language.

•Scilab has been designed to be an open system where the user can define new

data types and operations on these data types by using overloading.


Cont…
•A number of toolboxes are available with the system:
•• 2-D and 3-D graphics, animation
•• Linear algebra, sparse matrices
•• Polynomials and rational functions
•• Simulation: ODE solver and DAE solver
•• Scicos : a hybrid dynamic systems modeler and simulator
•• Classic and robust control, LMI optimization
•• Differentiable and non-differentiable optimization
•• Signal processing
•• Metanet: graphs and networks
•• Parallel Scilab using PVM
•• Statistics
•• Interface with Computer Algebra (Maple, MuPAD)
•• Interface with Tcl/Tk
•• And a large number of contributions for various domains.
Cont…
Scilab works on most Unix systems including GNU/Linux and on Windows
9X/NT/2000/XP/Vista/7. It comes with source code, on-line help and English user
manuals. Binary versions are available.

•Some of its features are listed below:

•• Basic data type is a matrix, and all matrix operations are available as built-in

•operations.

•• Has a built-in interpreted high-level programming language.

•• Graphics such as 2D and 3D graphs can be generated and exported to various


formats so that they can be included into documents.
How to get started with Scilab
•Whatever your platform is (i.e. Windows, Linux or Mac), Scilab binaries can be
downloaded directly from the Scilab homepage
•http://www.scilab.org
•or from the Download area
•http://www.scilab.org/download
•Scilab binaries are provided for both 32 and 64 bits platforms so that it matches
the target installation machine.

 Installing Scilab under Windows


 Installing Scilab under Linux
 Installing Scilab under Mac OS
Installing Scilab under Windows

•Scilab is distributed as a Windows binary and an installer is provided so


that the installation is really easy.

• Several comments may be done about this installation process.

•On Windows, if your machine is based on an Intel processor, the Intel


Math Kernel Library (MKL) enables Scilab to perform faster numerical
computations.
Installing Scilab under Linux
Under Linux, the binary versions are available from Scilab website as .tar.gz les.
There is no need for an installation program with Scilab under Linux: simply unzip
the le in one target directory.

<path>/scilab-5.2.0/bin/scilab.

•When this script is executed, the console immediately appears and looks exactly
the same as on Windows.

Nevertheless, it has one little drawback: the version of Scilab packaged for your
Linux distribution may not be up-to-date. This is because there is some delay
(from several weeks to several months) between the availability of an up-to-date
version of Scilab under Linux and its release in Linux distributions.

•For now, Scilab comes on Linux with a linear algebra library which is
optimized and guarantees portability. Under Linux, Scilab does not come
with a binary version of ATLAS, so that linearalgebra is a little slower for
that platform.
Installing Scilab under Mac OS
•Under Mac OS, the binary versions are available from Scilab website as a .dmg le.
This binary works for Mac OS versions starting from version 10.5. It uses the Mac OS
installer, which provides a classical installation process. Scilab is not available on
Power PC systems.

•Scilab version 5.2 for Mac OS comes with a Tcl / Tk library which is disabled for
technical reasons. As a consequence, there are some small limitations on the use of
Scilab on this platform.

•For example, the Scilab / Tcl interface (TclSci), the graphic editor and the variable
editor are not working. These features will be rewritten in Java in future versions of
Scilab and these limitations will disappear. Still, using Scilab on Mac OS system is
easy, and uses the shorcuts which are familiar to users of this platform.

• For example, the console and the editor use the Cmd key (Apple key) which is found
on Mac keyboards. Moreover, there is no right-click on this platform. Instead,
Scilab is sensitive to the Control-Click keyboard event.
How to get help
•The most simple way to get the online help integrated to Scilab is to use the
function help.
•To use this function, simply type "help" in the console and press the <Enter>
key, as in the following session.
help
•Suppose that you want some help about the optim function. You may try to
browse the integrated help, and the optimization section and then click on the
optim item to display its help.
•Another possibility is to use the function help, followed by the name of the
function which help is required, as in the following session.
help optim
•Scilab automatically opens the associated entry in the help.
•We can also use the help provided on Scilab web site
http://www.scilab.org/product/man
•A list of commercial books, free books, online tutorials and articles is presented
on the Scilab homepage:
http://www.scilab.org/publications
Mailing lists
The mailing list [email protected] is designed for all Scilab usage questions.
To subscribe to this mailing list, send an e-mail to
[email protected] .
•The mailing list [email protected] focuses on the development of Scilab, be it
the development of Scilab core or of complicated modules which interacts deeply
with Scilab core.
•To subscribe to this mailing list, send an e-mail to
[email protected] .
•These mailing lists are archived at:
http://dir.gmane.org/gmane.comp.mathematics.scilab.user
and
http://dir.gmane.org/gmane.comp.mathematics.scilab.devel
•Therefore, before asking a question, users should consider looking in the
archive if the same question or subject has already been answered.
Scilab wiki

•The Scilab wiki is a public tool for reading and publishing general information
about Scilab:

http://wiki.scilab.org

It is used both by Scilab users and developers to publish information about


Scilab. From a developer point of view, it contains step-by-step instructions to
compile Scilab from the sources, dependencies of various versions of Scilab,
instructions to use Scilab source code repository, etc...
Scilab Bugzilla
The Scilab Bugzilla http://bugzilla.scilab.org allows to submit a report each time
we and a new bug. It may happen that this bug has already been discovered by
someone else before. This is why it is advised to search in the bug database for
existing related problems before reporting a new bug. If the bug is not already
reported, it is a very good thing to report it, along with a test script. This test script
should remain as simple as possible, which allows to reproduce the problem and
identify the source of the issue.

•An efficient way of getting up-to-date information is to use RSS feeds. The RSS
feed associated with the Scilab website is

http://www.scilab.org/en/rss_en.xml

This channel delivers regularily press releases and general announces.


Getting help from Scilab demonstrations and macros

The Scilab consortium maintains a collection of demonstration scripts, which are


available from the console, in the menu ? >Scilab Demonstrations. It shown the
demonstration window.
Some demonstrations are graphic, while some others are interactive, which
means that the user must type on the <Enter> key to go on to the next step of the
demo.
The associated demonstrations scripts are located in the Scilab directory, inside
each module.
For example, the demonstration associated with the optimization module is
located in the le
<path>\scilab-5.2.0\modules\optimization\demos\datafit\datafit.dem.sce
Another method to nd some help is to analyze the source code of Scilab itself
(Scilab is indeed open-source!). For example, the derivative function is located in
<path>\scilab-5.2.0\modules\optimization\macros\derivative.sci
Getting started

We make our first steps with Scilab and present some simple
tasks we can perform with the interpreter.

There are several ways of using Scilab and the following


paragraphs present three methods:

 using the console in interactive mode,

 using the exec function against a file,

 using batch processing.


First step with SCILAB

•After launching Scilab, you can test the following commands


• help // To open Scilab's help
• help mot-cle // Get a description of the Keyword
• apropos mot-cle // Get pages related to the Keyword
• quit // To quit Scilab

•The command-line interface clear, clc et, clf erase respectively data in memory,
the commands on the screen and the plots. These commands should be executed
regularly to avoid errors and make the memory free.
The Console’s menu bar(1/6): File

•Among the functions under the


File drop-down menu that you
will quickly encounter are:

•Execute...: From here you can run


Scilab scripts (or from the Editor,
as seen later)
•Open…: Similar to the Open…
command in MS Office programs

•Change current directory…,


Display current directory:
Pay attention to those two, they
will be needed to tell Scilab
where to look for a script that you want to open
The Console’s menu bar(2/6): Edit

The functions under the Edit dropdown


menu are self-explanatory.

The Cut, Copy, and Paste


commands have their own icons in
the toolbar. You also find them by
right-clicking on the PC mouse

Be careful with Empty clipboard.


You may not be able to use Copy
after clicking it! (Happened to me)

I have used Select all a lot to


copy-paste the demos in this
presentation
The Console’s menu bar(3/6): Preferences

The functions under the


Preferences drop-down menu
are quite similar to what you
can find on a PC

I can only guess that Clear


History is similar to Clear
Private Data in Firefox, but
there is no Show History
alternative and Help is not
Helpful

Clear Console empties the


console. You achieve the same
by pressing F2

Change visual appearance of the Console


The Console’s menu bar(4/6): Control

I did not need the Control


drop-down menu a single time
while doing this presentation,
so obviously it is not very
Useful

My guess would be that the


Resume , Abort, and Interrupt
alternatives give the user a
way to interfere with the
execution of a program

The Help Browser is not very helpful and it does not even recognize the
Interrupt command
The Console’s menu bar(5/6): Applications

SciNotes: Opens Scilab’s Text


Editor (same as Launch
SciNotes in the toolbar)

Xcos: Opens Xcos

Matlab to Scilab translator:


Used to translate a Matlab .mfile
to a Scilab .sci file

Atoms: Opens the online


module manager

Variable Browser: Opens a list


with variables (same as the
browsevar; command)

Command History: Opens a list with commands used


The Console’s menu bar(6/6): Help alternatives

Scilab Web
Scilab Help: Same as the question resources
mark icon in the Toolbar

Scilab Demonstrations: Shows demos with few


comments (same command as the cogwheel in the toolbar).
At least the GUI/Uicontrols 2 demo causes Scilab to crash
The Console’s toolbar
The Atoms, Xcos, and Demonstrations
icons came with Scilab.
Launch Editor: Opens Scilab’s
Editor (SciNotes, another part
of its Integrated Development
Environment (IDE).
Basic tutorials seldom stress
the fact that normally we work
with (write, edit, save, run)
executable Scilab scripts on
the Editor, not on the Console.

The Editor is presented a few


slides below

Change Current Directory: It can also be


found under File in the menu bar. You need it
to point out from which directory (folder)
Scilab should search for a script that you want
to execute (run)
The console
 The first way is to use Scilab interactively, by typing commands in the console,
analyzing Scilab result, continuing this process until the final result is computed.
 This document is designed so that the Scilab examples which are printed here can
be copied into the console. The goal is that the reader can experiment by himself
Scilab behavior.
 This is indeed a good way of understanding the behavior of the program and, most
of the time, it allows a quick and smooth way of performing the desired
computation.
In the following example, the function disp is used in interactive mode to print out the
string "Hello! Welcome to SCILAB!".
-->s="Hello! Welcome to SCILAB!"
s = Hello! Welcome to SCILAB!
-->disp (s)
Hello! Welcome to SCILAB!
In the previous session, we did not type the characters "-->" which is the prompt, and
which is managed by Scilab. We only type the statement s="Hello World!" with our
keyboard and then hit the <Enter> key. Scilab answer is s = and Hello World!. Then
we type disp(s) and Scilab answer is Hello! Welcome to SCILAB!
The console
 When we edit the command, we can use the keyboard,
as with a regular editor. We can use the left and right !
arrows in order to move the cursor on the line and use
the <Backspace> and <Suppr> keys in order to x errors
in the text.
 In order to get an access to previously executed
commands, use the up arrow " key. This allows to
browse the previous commands by using the up " and
down # arrow keys.
 The <Tab> key provides a very convenient completion
feature. In the following session, we type the statement
disp in the console. -->disp
 Then we can type on the <Tab> key, which makes a list
appear in the console.
 Scilab displays a listbox, where items correspond to all
functions which begin with the letters "disp". We can
then use the up and down arrow keys to select the
function we want.
 The auto-completion works with functions, variables, les
and graphic handles and makes the development of
scripts easier and faster.
How to use: Command lines

•enter a command line by typing after the prompt

Hints:
Scilab is case-sensitive.
// is not interpreted (it is a
comment line)
% is used in front of defined
keywords (e.g. %e = 2.718)
The $ symbol stands for the
last row or last column index of
a matrix or vector.
The colon symbol stands for
“all rows” or “all columns”

System Arch 2007 (Fire Tom 2019/8/5


Wada)
The Editor (SciNotes)
Execute Save & execute

* The (Text) Editor is where


executable Scilab scripts are
written, maintained & run
* Open the Editor by clicking
on the Launch SciNotes icon
in the Console, or by clicking:
Applications\SciNotes

* A Scilab script is a text file


with a name of the type
*.sce (the alternative
*.sci is also used but
*.sce is the default)

* It is good practice to use


scripts also for small tasks.
Then all “projects” are saved But don’t forget to create a
and commented, ready for properly organized archive
reuse for your programs!
Editor menu bar: File

File commands that you are most


likely to run into:
* Recent files gives quick access to
recently edited scripts

* New opens a second tab for a


new script to be edited

*Open opens a saved script into


the Editor
*Open file in... and Save file in...
do not work in Scilab.

* Print is an ordinary print


command

*Close closes the file in case


Editor menu bar: Edit

Commands under Edit are


mostly self-explanatory. Note
however the following four:

Shift Right/Left:
Indent/unindent a row by one
step (this pair should be on the
toolbar)

Comment/Uncomment Selection:
Add/delete a comment
Editor menu bar: Preferences

The Preferences drop-down


menu allows you adjust Editor
settings to your liking

I had difficulties reading scripts


on the Editor (poor contrast
with default settings) and used

Set Colors... and Set Font to


change from default values
Editor menu bar: Execute

The Execute drop-down


window contains three options:

... file with no echo: A


simple execute command
(same as clicking the Execute
icon on the toolbar)

... file with echo: Executes The Execute commands used


the script and echoes it (shows to be simpler. I have no idea
it) on the Console why they changed them this
way. My recommendation is
to use the Execute icon on
... until the caret, with the toolbar (see next slide)
echo: Beats me, what it means
Editor toolbar
New... Opens a second
tab for a new script to
be edited (the same
command can be found
under File)

The Save icon looks like the


Dutch tricolor, but you’ll get
used to it. The next one is
Save as...

The Undo/Redo arrows The Execute (or Save &


are quite normal execute) icon is what you
normally use to run a script
The Paste icon is a
bit unusual (French?)
Editor toolbar

Console Editor

Graphics Window
Help Browser
The Editor

The editor can be accessed from the menu of


the console, under the Applications > Editor
menu, or from the console, as presented in the
following session.
--> editor ()
This editor allows to manage several les at the
same time, as presented in the figure, where
we edit five files at the same time.
There are many features which are worth to
mention in this editor. The most commonly used
features are under the Execute menu.
 Load into Scilab allows to execute the statements in the current le, as if we
did a copy and paste. This implies that the statements which do not end
with a ";" character will produce an output in the console.
 Evaluate Selection allows to execute the statements which are currently
selected.
 Execute File Into Scilab allows to execute the le, as if we used the exec
function. The results which are produced in the console are only those
which are associated with printing functions, such as disp for example.
The Editor

 We can also select a few lines in the script, right click (or Cmd+Click under Mac),
and get the context menu.

 The Edit menu provides a very interesting feature, commonly known as a "pretty
printer" in most languages.

 This is the Edit > Correct Indentation feature, which automatically indents the
current selection.

 This feature is extremelly convenient, as it allows to format algorithms so that the


if, for and other structured blocks can be easy to analyze.

 The editor provides a fast access to the inline help. Indeed, assume that we have
selected the disp statement.

 When we right-click in the editor, we get the context menu, where the Help about
"disp" entry allows to open the help associated with the disp function.
How to use:
Editor

•Programming: You can open SCIPAD to write your program

Hints:
When save file, remember write filename + extension
(*.sce , *.sci )
.sce files are executed
.sci files are loaded to be used when we need them
Built-in functions
Below is a list of common math functions in Scilab. A full list of built-in
functions can be found under Help\Elementary Functions, which also
explains requirements on arguments (there are both mandatory and
optional arguments).
Scilab Variables
• Special variables:
– ans: default variable name for the result.
– %pi: π = 3.1415926
=> % is used in front of defined keyword
- %i : i is an imaginary number
- %inf : infinity (∞)
ASCII stands for American Standard Code for Information Interchange

• Commands involving variables:


-who: lists the names of the defined variables
-whos: lists entire contents of the workspace, including
functions, libraries, constants
-clear: clears all variables
-clc: clears the command window
clf: clears all plots in the active graphic window
-->// Let us check cos(x)^2+sin(x)^2=1
-->// We use variable %pi to check it
-->C=cos(%pi)
C =
- 1.
-->S=sin(%pi)
S =
1.225D-16
-->C^2+S^2
ans =
1.

41
The fact that obtained value of sin(Pi) is
not exactly equal to 0 is a consequence of
the fact that Scilab stores the real numbers
with limited precision.

42
Complex Numbers

Scilab provides complex numbers, which are stored


as pairs of floating point numbers. The pre-defined
variable %i represents the mathematical imaginary
number i with i2 = -1.

43
-->x=1+%i
x =
1. + i
-->x'
ans =
1. - i
-->y=1-%i
y =
1. - i
-->real(y)
ans =
1.
-->imag(y)
ans =
- 1.
-->x*y
ans =
2.
44
Lists

In Scilab a list can be defined using the list(); function:


In the example above the list variable named list variable contains 5 types of data:

• Real
• String
• Matrix
• Boolean
• Polynomial

Example:
 list_variable=list(142, "someText", [1 4;6 2], %T, %s^2+1)
The type and typeof functions

Scilab can create various types of variables, such as matrices, polynomials,


booleans, integers and other types of data structures. The type and typeof
functions allow to inquire about the particular type of a given variable. The type
function returns a floating point integer while the typeof function returns a string.

type Returns a string


typeof Returns a floating point integer

-->A = eye (2 ,2)


A = 1. 0.
0. 1.
--> type ( A )
ans = 1.
 typeof ( A )
ans = constant

These two functions are useful when processing the input arguments of a function.
The type and typeof functions
Strings

Strings can be stored in variables, provided


that they are delimited by double quotes “ “ .
The concatenation operation can be done
with the “+” operator.

48
Strings
-->X="Mathematics"
X =
Mathematics

-->Y="Workshop"
Y =
Workshop

-->X+Y
ans =
MathematicsWorkshop

49
Strings

50
Strings

51
Strings

52
Polynomials
Scilab allows to manage univariate polynomials. The implementation is based
on a vector containing the coefficients of the polynomial. At the user's level, we
can manage a matrix of polynomials. Basic operations like addition,
subtraction, multiplication and division are available for polynomials. We can,
of course, compute the value of a polynomial p(x) for a particular input x.
Moreover, Scilab can perform higher level operations, such as computing the
roots, factoring or computing the greatest common divisor or the least common
multiple of two polynomials. When we divide one polynomial by another
polynomial, we obtain a new data structure representing the rational function.

53
Polynomials

54
Polynomials

55
Polynomials

56
Polynomials

57
Scilab Arithmetics Operators
Operator Description
+ Addition
- Subtraction
.* Multiplication (element wise)
./ Right division (element wise)
.\ Left division (element wise)
= Assignment operator,e.g. a = b,
(assign b to a)
: Colon operator (Specify Range )
.^ Power (element wise)
' Transpose
* Matrix multiplication
/ Matrix right division
\ Matrix left division
; Row separator in a Matrix
^ Matrix power
Calculations at Command Lines

Scilab as a calculator Assigning Variables


» -5/(4.8+5.32)^2 » a = 2; Semicolon
ans = » b = 5; suppresses
-0.0488213 screen output
» a^b
>>(3+4*%i)*(3-
ans = Results
4*%i) assigned to
ans = 25. 32. “ans” if name
» cos(%pi/2) ans = » x = not specified
6.123D-017 5/2*%pi;
» exp(acos(0.3)) ans » y =
= sin(x) y =
3.5470053 1. ( ) parentheses for
» z = asin(y) function inputs

z =
1.5707963
Computing terminology: brief introduction

Arguments: Values provided as inputs to a command (input arguments) or


returned by the command (output arguments)

Command: A user-written statement that provides instructions to the computer


(“statement” is an often used alternative)

Default: Action taken or value chosen if none has been provided

Display: To output a listing of text information on the computer Screen

Echo: To display commands or other input typed by the user

Execute: To run a program or carry out the instructions specified in a Command

Print: To output information on a computer printer (often confused with “display”)

Returns: Results provided by the computer in response to a command


Rounding functions
Booleans
Boolean variables store true or false value. In Scilab,
true is written with %t or %T and false is written with
%f or %F.

64
-->a=%T
a =
T
-->b=(0==1)
b =
F
-->a&b
ans =
F

65
Floating point
•ceil — round up
•clean — cleans matrices (round to zero small entries)
•double — conversion from integer to double precision representation
•fix — round towards zero
•floor — round down
•format — number printing and display format
•frexp — dissect floating-point numbers into base 2 exponent and mantissa
•ieee — set floating point exception mode
•int — round towards zero
•isinf — check for infinite entries
•isnan — check for "Not a Number" entries
•nearfloat — get previous or next floating-point number
•nextpow2 — next higher power of 2.
•number_properties — determine floating-point parameters
•round — round to nearest integer
66
Calendar

67
Example -1

68
Example -2

69
Example -3

70
Example -4

71
Example -5

72
Example -6

73
Assignment - 1
1. What are the other ways of obtaining online help in Scilab, other than
typing “help” at the command prompt?
2. Where are the demo programs that demonstrate Scilab's capabilities?
3. Where can you find user contributed documents on using and applying
Scilab? What are the categories for these documents? Which categories
interest you?
4. How can you search for a word or pattern in the Scilab online help
browser?
5. Can you use the built-in variable “ans” in your calculations? If so, is it a
good idea to do so or is it better to use your own named variables?
6. When do you think it is useful to use the semicolon (;) to suppress the
output of a Scilab statement?
7. What are the rules for choosing names for variables in Scilab? Can you
use a numeric character as the first character? Can you use
underscore ( _ ) as the first character? Can you use special characters,
such as -, +, /, ? in a variable name?
8. Can you change the font used by Scilab
9. What is the command to clear the screen?
10. What is the short cut key to clear the screen?
11. What is command history? What are the shortcut keys to use the
74
command history?
Assignment - 1
12. List areas within your proposed branch of specialization where Scilab can be a
useful tool.
13. Is there a command to record all commands that you type and save them to a
file so that you can see them later?
14. Can you describe some useful application of the diary command?
15. Can you customize Scilab startup to suit your specific needs?
16. What are the available data types in Scilab?
17. What is the command to list all variables in the Scilab workspace
whose name begins with the letters “sa”?
18. What is the command to list all variables in the Scilab workspace of
type boolean?
19. What is the Scilab constant for the value of π?
20. What is the command to find the Scilab current working directory?
21. Where can you find the Scilab current working directory?
22. How can you change the Scilab current working directory to a different
location?
23. Why is it important to know the Scilab current working directory?
24. Is Scilab a strongly typed language?
75
Any questions?

76

You might also like