Getting Started With Scilab-Seminario
Getting Started With Scilab-Seminario
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.
These are the sources from where you can download Scilab binaries:
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.
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
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
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
•
Anonym May 23, 2011, 4:01 a.m.
Do any major companies use this software?
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.
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.
Note:
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. 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)
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
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
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.
-->2 + 3
ans =
5.
-->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:
-->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:
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.
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.
Trigonometric Functions
Logarithmic Functions
Hyperbolic Functions
-->a = 2; b = 3; c = -4;
-->disc = b^2 - (4 * a * c)
disc =
41.
r1 =
0.8507811
r2 =
-2.3507811
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.
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.
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.
The above command lists all the objects in the Workspace and displays the name,
type, size and memory used by each object.
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.
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.
-->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.
-->chdir('C:\Users\Satish\My 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)
-->save('~/prj/test.dat', x, y, z)
-->load('~/Scilab/test.dat') // *nix
-->a, b, c
-->pwd
-->save('test.dat', a, b, c)
-->clear a b
-->a
-->b
-->c
-->clear c
-->// ERROR
-->c
-->load('test.dat')
-->a, b, c
Important Notes
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:
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
-->c = [1 2 3
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.
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:
-->z = diag([1 2 3], -1) // Same as above, but placed one place below
the main diagonal
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
-->a = rand(3, 3)
-->a = rand(3, 3) * 10
-->// b is transpose of a
-->b = a'
-->c = a + b
-->d = a - b
-->x = a * b
-->// Solve linear equations [A] {x} = {b} for unknowns {x}
-->x = a \ b
-->x = a^2
-->y = a^3
-->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
-->b = a.^2
Can you explain what is a .^3? Is a .^ 0.5 valid? If yes, what does it represent?
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 = 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.
Ranges
Range is a sequences of numbers that can be generated using the range operator,
namely, colon(:). You can define a variety of ranges:
ans =
1. 2. 3. 4. 5.
-->1:2:10 // increment is 2
qns =
1. 3. 5. 7. 9.
ans =
-->4:-1:1 // decrement is 1
ans =
4. 3. 2. 1.
ans =
4. 3.5 3. 2.5 2.
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:
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)
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
-->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:
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.
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()
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
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:
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.
or, alternately
-->p = poly([2 3], 'x', 'r')
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 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.
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:
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)');
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.
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:
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:
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 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
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
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.
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:
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:
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. 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:
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:
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)
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:
Here are some rules you must remember about output arguments and output
parameters:
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:
Objectives
In this session we will learn the following:
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
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.
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).
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
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
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:
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. 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.
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
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.
Objectives
In this session you will learn the following:
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)
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 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)
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.
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]
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:
To get you started, I will list a few problems from structural engineering:
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