Sci Lab For Numerical
Sci Lab For Numerical
Sci Lab For Numerical
1
Scilab Quick Reference (Early Access) i
Contents
1 Scilab Basics 3
1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Mode of Scilab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Some useful windows in Scilab . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Editing variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Scalar computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Continuing long command . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Boolean expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8 Built-in math functions and variables . . . . . . . . . . . . . . . . . . . 13
1.9 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Matrix construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Matrix operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Elementwise operation . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Expanding a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Submatrix extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Replacing a submatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Deleting matrix or submatrix . . . . . . . . . . . . . . . . . . . . . . . 27
Deleting submatrix with matrix as index . . . . . . . . . . . . . . . . . 28
Matrix manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Element lookup in a matrix . . . . . . . . . . . . . . . . . . . . . . . . 29
Auto-generation of matrices . . . . . . . . . . . . . . . . . . . . . . . . 32
Kinds of matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.10 Special types of matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 36
List, Struct and Typed List . . . . . . . . . . . . . . . . . . . . . . . . 36
Other special types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Scilab Quick Reference (Early Access) ii
2 Programming Basics 58
2.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.4 Scipad editor window . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.5 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.7 Nested function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2.8 Multiple functions in one file . . . . . . . . . . . . . . . . . . . . . . . . 65
2.9 Mixed scripts and functions . . . . . . . . . . . . . . . . . . . . . . . . 66
2.10 Inline function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
2.11 Sequential statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
if-elseif-else-end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
select-case-else-end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
2.12 Looping statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
for-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
while-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
2.13 Nested loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Scilab Quick Reference (Early Access) iii
3 Plotting Basics 91
3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.4 Basic plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.5 plot2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
plot2dx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.6 Plotting a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.7 Customizing plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Grids and ticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Label and title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Legend and caption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Multiple plot in a graphics window . . . . . . . . . . . . . . . . . . . . 101
Adding text in a plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Capturing points from the plot . . . . . . . . . . . . . . . . . . . . . . 104
Drawing plot later . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Customizing plot graphically . . . . . . . . . . . . . . . . . . . . . . . . 106
3.8 Animating 2D plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
3.9 Other types of plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Data plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Surface plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Scilab Quick Reference (Early Access) iv
4 Dialogs 115
4.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.4 messagebox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.5 progressionbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
4.6 waitbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
4.7 x dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
4.8 x mdialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
4.9 x choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
4.10 x choose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
4.11 x matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
4.12 Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
List of Tables
1 Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2 Variable types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3 Boolean variable, comparison operator, and boolean functions . . . . . 14
4 Math built-in variables and functions . . . . . . . . . . . . . . . . . . . 15
5 Operators used in matrix operation . . . . . . . . . . . . . . . . . . . . 17
6 Operators used in elementwise matrix operation . . . . . . . . . . . . . 19
7 Operators and syntax used for extracting element or submatrix . . . . 22
8 Functions used to manipulate a matrix . . . . . . . . . . . . . . . . . . 30
9 Functions and syntax for searching elements in a matrix that satisfies a
criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
10 Functions used to generate a matrix . . . . . . . . . . . . . . . . . . . . 33
11 Kinds of matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
12 List, struct and tlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
13 Functions used for creating and manipulating a special matrix . . . . . 39
14 Other functions used to manipulate a number in scilab . . . . . . . . . 41
15 Formatting functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
16 Operators used in polynomial operation . . . . . . . . . . . . . . . . . . 46
17 Functions used to manipulate a polynomial . . . . . . . . . . . . . . . . 46
18 Functions used to manipulate complex numbers . . . . . . . . . . . . . 49
19 Transposing a complex matrix . . . . . . . . . . . . . . . . . . . . . . . 50
20 Functions used for plotting and customizing plot . . . . . . . . . . . . . 51
21 Break and continue statement for loop . . . . . . . . . . . . . . . . . . 74
22 Variable input and output . . . . . . . . . . . . . . . . . . . . . . . . . 75
23 Input data from user and display . . . . . . . . . . . . . . . . . . . . . 78
24 Formatting printing of output . . . . . . . . . . . . . . . . . . . . . . . 79
25 Placeholder for printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
26 External file processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
27 Error handling commands . . . . . . . . . . . . . . . . . . . . . . . . . 83
28 String processing syntax . . . . . . . . . . . . . . . . . . . . . . . . . . 85
29 Executing scilab command in string form . . . . . . . . . . . . . . . . . 85
30 Regular expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
31 Date and time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
32 Miscellaneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
33 Line specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Scilab Quick Reference (Early Access) vi
List of Figures
1 Scilab Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Scilab console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3 Scilab editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4 Help window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5 Graphics Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
6 Scicos Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7 Variable editor window . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8 Axes properties editor menu . . . . . . . . . . . . . . . . . . . . . . . . 52
9 Axes properties editor window . . . . . . . . . . . . . . . . . . . . . . . 53
10 Sample plot output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
11 Scipad editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
12 Plot output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
13 Plot2d sample plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
14 Multiple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
15 Text to a plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
16 Axes properties editor menu . . . . . . . . . . . . . . . . . . . . . . . . 107
17 Axes properties editor window . . . . . . . . . . . . . . . . . . . . . . . 108
18 Digital signal plot output . . . . . . . . . . . . . . . . . . . . . . . . . . 112
19 messagebox sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
20 progressionbar sample . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
21 waitbar sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
22 xdialog sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
23 x mdialog sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
24 x choices sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
25 x choose sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
26 x matrix sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Scilab Quick Reference (Early Access) Acknowledgment viii
Acknowledgment
First and foremost, I would like to say thank you to our Lord God for giving me
such patience to pursue this handbook.
To start, I want to extend my gratitude to God’s disciple who help me out with the
evaluation of this handbook. Starting with my one and only younger brother, Allen,
for his loving support and continuing loyalty to me. When I finished the first draft of
chapter 1 and chapter 2, he is my first student to evaluate my work. Thanks to him, I
did a lot of corrections and additional subsections to include in each chapter which is
very relevant.
To my parents who did love me unconditionally and support any work I made, may
it be beneficial or not to them or to me as long as I am enjoying of what I am doing.
Their support, both of them, are incomparable that gives me the fighting spirit to finish
this handbook.
To the people who evaluates this handbook thanks to all of you guys. From ECE
172 and ES 84 batch 2008-2009 2nd semester. To Rogelio who learn Scilab using this
as a reference important additional subsection such as function in string is added.
Thanks to my experience in MATLAB it really help me a lot. Influences me to
outline the topics as it is.
Scilab Quick Reference (Early Access) Preface ix
Preface
Scilab can be used to simulate engineering applications such as Control systems,
power system application, numerical methods and other advance engineering math ap-
plications. But for the sake of a minified handbook the discussion will be limited to
minimal capabilites of Scilab. Every end of the chapter provides exercise problems to
assess your skill.
This is a minified1 handbook for Scilab programming serve as a quick reference for
learning Scilab programming. Inside are not just the proper syntax but also the tricks
of code used to simplify commands.
This handbook is divided into two volumes outlined below.
Volume 1 covers:
Chapter 1, Scilab Basics, serve as a quick start for using Scilab in the areas of
mathematical operations, matrix manipulation, complex numbers, polynomials and
plotting. Some topics are tackled in detail in a separate chapter such as plotting for
further discussion.
Chapter 2, Programming Basics, discusses the basic syntax of creating a function or
script. Sample code are also provided for live testing. Some features of character and
string manipulation are also included.
Chapter 3, Plotting Basics, shows the different and easiest way of plotting a data
and dynamic setting of its properties.
Chapter 4, Dialogs, shows how to use popup dialogs to display visually the results.
Chapter 5, Graphical User Interface, extends the dialog boxes into a pack of user
interfaces that interacts with user actions such as entering text, clicking a button, up-
dating a slider, etc. GUI programming concerns about the visual user interface and its
corresponding layout and arrangement in a graphics window.
Conventions
This handbooks assumes that you have already installed Scilab in your machine.
Below are the conventions used in this book.
• Codes are displayed in Courier format.
Scilab Quick Reference (Early Access) Preface 1
• Code with --> before the command are executed in the console.
• Code without --> are saved in an external file then loaded in scilab.
• Enclosed in <> are optional arguments, may or may not be present.
• Keywords categories:
– %name - variables.
– name - functions and reserved words. Function name is followed by paren-
thesis specifying argument list. Parenthesis can be eliminated if there are no
arguments needed.
– symbol - operators.
Chapter 1
Scilab Basics
Scilab Quick Reference (Early Access) Chapter 1: Basics 3
1 Scilab Basics
1.1 Objectives
• To understand the features of scilab and its significance in numerical simulation.
• To know how to create a matrix in scilab.
• To know how to manipulate matrix.
• To know special type of matrices such as sparse and its impact in computing large
matrices with more zero elements.
• To know other types of flexible matrices such as cell, list, and struct.
• To know the complete reference for built-in math functions in Scilab.
• To know the basic of plotting a data and a function.
• To know how to manipulate polynomials.
• To know how to manipulate complex numbers in Scilab.
1.3 Introduction
Scilab is a numerical software that process data by batch, that is, stored in a ma-
trix. Mathematical capabilites of Scilab aside from built-in math functions and matrix
manipulation involve plotting, polynomial operation and complex numbers.
1.6 Basics
Basic usage of scilab as a numerical software is a calculator. Table 1 shows the scalar
and matrix computation built-in in Scilab.
Scilab Quick Reference (Early Access) Chapter 1: Basics 5
Rules: Must start with [a-z], [A-Z], or, underscore(_) followed by [a-z], [A-Z],
underscore(_), or, [0-9].
Invalid: 5var
Editing variables
Keywords: editvar
Sample Code
Start code
-->a = eye(3,3)
a =
1. 0. 0.
0. 1. 0.
Scilab Quick Reference (Early Access) Chapter 1: Basics 11
Code Type
1 Real or complex constant matrix.
2 Polynomial matrix.
4 Boolean matrix.
5 Sparse matrix.
6 Sparse boolean matrix.
7 Matlab sparse matrix.
8 Matrix of integers stored on 1 2 or 4 bytes.
9 Matrix of graphic handles.
10 Matrix of character strings.
11 Un-compiled function (Scilab code).
13 Compiled function (Scilab code).
14 Function library.
15 List.
16 Typed list (tlist).
17 Matrix oriented typed list (mlist).
128 Pointer (See lufact).
129 Size implicit polynomial used for indexing.
130 Scilab intrinsic (C or Fortran code).
0. 0. 1.
Scalar computation
Sample Code
Start code
--> 1 + 1 //scalar addition
ans =
2.
Scilab Quick Reference (Early Access) Chapter 1: Basics 13
Note: Putting a semicolon at the end of a statement suppresses the output to display.
For variable assignment, variable is already registered in a workspace but not echoed to
the command line. ans is the default variable if no assigned variable specified.
Long commands that is messy when force to fit to a single line can be sliced up to
multiple lines using ellipsis (3 dots).
Sample Code
Start code
-->a = 1+...
-->1
a =
2.
End code
Command Description
%t A variable that represent true value.
%f A variable that represent false value.
> Greater than.
>= Greater than or equal.
< Less than.
<= Less than or equal.
== Equal.
~= Not equal. Same as <>.
& And operator.
~ Not operator.
| Or operator.
isdef Check if variable is defined in a workspace.
isempty Check if variable is empty.
isnan Check if variable is not-a-number.
isreal Check if variable is real or complex.
isinf Check if variable is infinite.
isequal Check if 2 objects are equal.
1.9 Matrix
Built-in math functions is also applicable to a matrix.
Matrix are created by enclosing array of numbers by a pair of brackets. Rows are
separated by a return key or a semicolon. Columns are separated by a space or a
comma.
Matrix construction
Sample Code
Start code
-->//1st solution
-->//comma as column separator
-->//semicolon as row separator
Scilab Quick Reference (Early Access) Chapter 1: Basics 15
Command Description
%pi Equivalent to π = 3.1415927.
%e Equivalent to e = 2.7182818.
cos(t) Cosine of angle t where t is in radians.
acos(x) Arccosine of x. cos−1 (x). Returns the result in radians.
sin(t) Sine of angle t where t is in radians.
asin(x) Arcsine of x. sin−1 (x). Returns the result in radians.
tan(t) Tangent of angle t where t is in radians.
atan(x) Arctangent of x. tan−1 (x). Returns the result in radians.
et + e−t
cosh(t) Cosine hyperbolic. .
2
t=acosh(x) Arcosine hyperbolic. cosh(t) = x.
et − e−t
sinh(t) Sine hyperbolic. .
2
t=asinh(x) Arcsine hyperbolic. sinh(t) = x.
sinh(t)
tanh(t) Tangent hyperbolic. .
cosh(t)
t=atanh(x) Arctangent hyperbolic. tanh(t) = x.
abs(n) Absolute value. Returns a positive value for a scalar argument, n.
v=log(x) Natural logarithm with base e. ev = x
v=log10(x) Common logarithm with base 10. 10v = x
v=log2(x) Logarithm with base 2. 2v = x
v=exp(x) ex . Same as %e^x.
√
v=sqrt(x) Square root. v = x equivalent to v = x1/2 .
--> a = [1,2,3;4,5,6;7,8,9]
a =
1. 2. 3.
4. 5. 6.
7. 8. 9.
-->//2nd solution
-->//return key as row separator
-->//space as column separator
--> b = [6 1 3
9 0 1
3 2 8]
b =
6. 1. 3.
9. 0. 1.
3. 2. 8.
-->//Combination of 1st and 2nd solution
-->//return key and semicolon as row separator
-->//space and comma as column separator
--> c = [5,2,-3
1,0,3;10,-8 3]
c =
5. 2. - 3.
1. 0. 3.
10. - 8. 3.
End code
Matrix operation
Command Description
+ Matrix addition.
- Matrix subtraction.
* Matrix multiplication. Inner dimension must agree, i.e., column
count of the first operand must be equal to the row count of the
second operand. The resulting dimension is that the resulting row
equals to the row of the first operand and resulting column equals
to the column of the second operand
/ Matrix division. A/B = A ∗ B −1
\ Matrix back-division. A\B = A−1 ∗ B
^ Matrix exponentiation with scalar power. Matrix exponent is pos-
sible but not practical.
-->b = [3,7,1;8,4,7;0,2,1];
-->a+b
ans =
7. 10. 7.
9. 9. 14.
6. 3. 10.
-->a-c
ans =
- 1. 1. 9.
0. 5. 4.
- 4. 9. 6.
-->a*c
ans =
-->a/c
ans =
-->a\c
ans =
Elementwise operation
Each elements that corresponds to their position are evaluated one-by-one. Matrix
addition and matrix subtraction are already elementwise operation but not multiplica-
tion, division and exponentiation. See table 6.
Sample Code
Start code
Scilab Quick Reference (Early Access) Chapter 1: Basics 19
Command Description
.* Matrix element-by-element multiplication.
./ Matrix element-by-element division.
.^ Matrix element-by-element exponentiation.
.\ Matrix element-by-element back-division.
-->a = [4,3,6;1,5,7;6,1,9];
-->b = [3,7,1;8,4,7;0,2,1];
-->a .* b
ans =
12. 21. 6.
8. 20. 49.
0. 2. 9.
-->b ./ a
ans =
-->a .^ b
ans =
64. 2187. 6.
1. 625. 823543.
1. 1. 9.
-->a .\ b
ans =
0. 2. 0.1111111
End code
Expanding a matrix
Matrix in scilab is dynamic and can expand and shrink in dimension. See sample
code below.
Start code
-->//starting as a scalar
-->e=1,esize=size(e)
e =
1.
esize =
1. 1.
-->e(2)=3,esize=size(e)
e =
1.
3.
esize =
2. 1.
-->e(1,4)=-1,esize=size(e)
e =
1. 0. 0. - 1.
3. 0. 0. 0.
esize =
2. 4.
Scilab Quick Reference (Early Access) Chapter 1: Basics 21
-->e(3,3)=5,esize=size(e)
e =
1. 0. 0. - 1.
3. 0. 0. 0.
0. 0. 5. 0.
esize =
3. 4.
-->e(4,:)=[2 9 8 1],esize=size(e)
e =
1. 0. 0. - 1.
3. 0. 0. 0.
0. 0. 5. 0.
2. 9. 8. 1.
esize =
4. 4.
-->//size of matrix e is changing
End code
Submatrix extraction
Table 7 shows the symbol and operator used to extract element of submatrix of a
given matrix.
Initializing matrix
Start code
-->a = [4,3,6;1,5,7;6,1,9]
a =
4. 3. 6.
1. 5. 7.
Scilab Quick Reference (Early Access) Chapter 1: Basics 22
Command Description
$ Last index.
: All indices.
a(r,c) Accessing rth row cth column. r and c can be a scalar, vector or a
matrix.
a(n) Accessing nth number counted from top to bottom then left to
right. n can be a scalar, vector or a matrix.
6. 1. 9.
-->b = [3,7,1;8,4,7;0,2,1]
b =
3. 7. 1.
8. 4. 7.
0. 2. 1.
-->c = [a,b]
c =
4. 3. 6. 3. 7. 1.
1. 5. 7. 8. 4. 7.
6. 1. 9. 0. 2. 1.
End code
Scalar index
4.
-->//accessing row 2, col 3
-->a(2,3)
Scilab Quick Reference (Early Access) Chapter 1: Basics 23
ans =
7.
-->//accessing row 3, last col
-->a(3,$)
ans =
9.
-->a(5)
ans =
5.
End code
Vector index
Syntax: a([ri,rj,rk],[cp,cq,cr])
The result is
aip aiq air
ajp ajq ajr
akp akq akr
Start code
-->//accessing rows 1 and 2, col 3
-->a([1,2],3)
ans =
6.
Scilab Quick Reference (Early Access) Chapter 1: Basics 24
7.
-->//accessing rows 1 and 2, cols 2 and 3
-->a([1,2],[2 3])
ans =
3. 6.
5. 7.
-->//accessing rows 1 and 3, all columns
-->a([1 3],:)
ans =
4. 3. 6.
6. 1. 9.
6.
9.
-->a([1,3,5,9])
ans =
4.
6.
5.
9.
-->//error: accessing submatrix beyond the dimension
-->a([1 2 4],:)
!--error 21
Invalid index.
End code
Matrix index
Scilab Quick Reference (Early Access) Chapter 1: Basics 25
Syntax: a([ri,rj;rk,rm],[cp,cq;cr,cs])
4. 7. 6. 1.
1. 4. 7. 7.
1. 4. 7. 7.
6. 2. 9. 1.
-->c([1,2],[1,3;5,6])
ans =
4. 7. 6. 1.
1. 4. 7. 7.
-->c([1,2;2,3;4,8])
ans =
Scilab Quick Reference (Early Access) Chapter 1: Basics 26
4.
1.
3.
1.
6.
7.
End code
Replacing a submatrix
When replacing a submatrix, first extract the submatrix and then store a new ma-
trix having the same dimension with the extracted one. If the original submatrix
does not have the same dimension as the new matrix, the error would be ’Inconsistent
row/column dimensions’ with error code equal to 6.
Sample Code
Start code
-->//creating a 3x4 matrix and store to d
-->d=[1,2,6,2;3,9,8,7;3,7,5,1]
d =
1. 2. 6. 2.
3. 9. 8. 7.
3. 7. 5. 1.
-->//replace submatrix comprising of 2nd and last row then 3rd and last column
-->// by [9 8]
-->// [7 6]
-->d([2,$],[3,$]) = [9,8;7,6]
d =
1. 2. 6. 2.
3. 9. 9. 8.
3. 7. 7. 6.
Scilab Quick Reference (Early Access) Chapter 1: Basics 27
End code
Sample Code
Start code
-->//using the same matrix as initialized above
-->a,b,c
a =
4. 3. 6.
1. 5. 7.
6. 1. 9.
b =
3. 7. 1.
8. 4. 7.
0. 2. 1.
c =
4. 3. 6. 3. 7. 1.
1. 5. 7. 8. 4. 7.
6. 1. 9. 0. 2. 1.
-->//deleting all elements in matrix, a
-->a=[]
a =
[]
-->//deleting rows 1 and 2
-->b([1,2],:) = []
b =
Scilab Quick Reference (Early Access) Chapter 1: Basics 28
0. 2. 1.
-->//deleting columns 2 and 3
-->c(:,[2 3])=[]
c =
4. 3. 7. 1.
1. 8. 4. 7.
6. 0. 2. 1.
-->//error: 5th column is out of bounds
-->c([1,2],[1,5])
!--error 21
Invalid index.
End code
If the index is a matrix, the result is the submatrix retaining the matrix index for
the row and the remaining columns eliminating the matrix index in the column.
Sample Code
Start code
-->//recall c
-->c
c =
4. 3. 7. 1.
1. 8. 4. 7.
6. 0. 2. 1.
-->// same as c([1,2;3,2],4)
-->// since columns [1,2,3] are eliminated
-->c([1,2;3,2],[1,3;2,3])=[]
c =
1.
Scilab Quick Reference (Early Access) Chapter 1: Basics 29
1.
7.
7.
End code
Matrix manipulation
9. 9. 2. 3.
7. 1. 5. 6.
2. 9. 8. 3.
1. 1. 10. 5.
-->and(g)
ans =
-->or(g)
ans =
-->g(4,3)=0
g =
Scilab Quick Reference (Early Access) Chapter 1: Basics 30
Command Description
diag(a) Diagonal of a matrix. If a is a matrix, it extracts the diagonal
elements of a matrix. If a is a vector, it creates a matrix placing
all elements along the diagonal with zero other elements.
trace(a) Sum up the diagonal elements of a square matrix. Error if argument
is not a square matrix.
[L,U]=lu(a) Perform LU decomposition to a matrix. Error if output arguments
is not atleast 2.
rref(c) Reduced-row echelon form of matrix c where c is an augmented
matrix result of a and b. Uses LU transformations. It can also
solve any kind of matrix.
det(a) Solves for the determinant of a matrix. Error if a is a vector.
inv(a) Solves for the inverse of a matrix. Error if a is a vector.
a’ Transpose of a matrix.
unique Returns the unique set of numbers in a given matrix.
max(a) Maximum value of a given matrix. max(a,’r’) returns the maxi-
mum value in every column resulting to a row vector. max(a,’c’)
returns the maximum value in every row resulting to a column
vector.
min(a) Minimum value of a given matrix. min(a,’r’) returns the mini-
mum value in every column resulting to a row vector. min(a,’c’)
returns the minimum value in every row resulting to a column vec-
tor.
prod(a) Product of all elements in a matrix. prod(a,’r’) returns the
product of elements in every column resulting to a row vector.
prod(a,’c’) returns the product of elements in every row resulting
to a column vector.
sum(a) Sum of all elements in a matrix. sum(a,’r’) returns the product
of elements in every column resulting to a row vector. sum(a,’c’)
returns the product of elements in every row resulting to a column
vector.
cumprod(a) Cumulative product of a matrix. cumprod(a,’r’) returns the cu-
mulative product of elements in every column resulting to a ma-
trixmatrix. cumprod(a,’c’) returns the cumulative product of
elements in every row resulting to a matrix.
cumsum(a) Cumulative sum of a matrix. cumsum(a,’r’) returns the cumula-
tive sum of elements in every column resulting to a matrixmatrix.
cumsum(a,’c’) returns the cumulative sum of elements in every
row resulting to a matrix.
flipdim(a,d) Flip matrix vertically or horizontally. If d=1, matrix is flipped ver-
tically, same as a($:-1:1,:). If d=1, matrix is flipped horizontally,
same as a(:,$:-1:1).
Command Description
and(m) Test if a vector or matrix are all true or greater than zero. Checking
by row or by column: and(m,’r’) - checks each column and return
a row vector;and(m,’c’) - checks each row and return a column
vector;
or(m) Test if a vector or matrix has atleast 1 true or greater than
zero.Checking by row or by column: or(m,’r’) - checks each col-
umn and return a row vector;or(m,’c’) - checks each row and
return a column vector;
find(m) Find indices of a given boolean condition from a given vector or
matrix greater than zero. find(m bool_op n) where m is a ma-
trix, bool op is a boolean operator such as <,<=,>,>=,==,<>,~=, n
is the limit number. If values are to be displayed instead of indices
use m(find(m bool_op n)).
m(m bool_op n) Display the elements that satisfies the condition.
Table 9: Functions and syntax for searching elements in a matrix that satisfies a criteria
9. 9. 2. 3.
7. 1. 5. 6.
2. 9. 8. 3.
1. 1. 0. 5.
-->and(g)
ans =
-->or(g)
ans =
1. 2. 5. 7. 11. 14.
Scilab Quick Reference (Early Access) Chapter 1: Basics 32
9.
7.
9.
9.
8.
6.
- 1. - 1. 2. 3.
- 1. 1. 5. - 1.
2. - 1. - 1. 3.
1. 1. 0. 5.
End code
Auto-generation of matrices
1. 0. 0.
0. 1. 0.
0. 0. 1.
-->ones(3,3)
ans =
Scilab Quick Reference (Early Access) Chapter 1: Basics 33
Command Description
eye(r,c) Identity matrix.
ones(r,c) Matrix with elements all equal to 1.
zeros(r,c) Matrix with elements all equal to 0.
rand(r,c) Matrix with elements generated randomly between 0 to 1. Use
to generate test matrix. Formula: int(rand(m,n)*maxN+startN),
generates an m-by-n matrix with each elements randomly selected
between startN and maxN .
linspace(n,x,p) Linear spacing of a vector with specified number of points. n as
minimum number, x as maximum number, and p as the number of
points.
logspace(n,x,p) Same as linspace but spaced logarithmically.
n:i:x Linear spacing of a vector. n as minimum, x as maximum, and
i as interval from n and x. Valid syntax: n:x has default i=1.
Decreasing interval starting from maximum has a syntax, x:-i:n.
testmatrix(t,n) Generates an nxn matrix depending on the type
t=’magi’|’frk’|’hilb’. Type can be ’magi’ to generate a magic
square, ’frk’ to generate a Franck matrix, and ’hilb’ to generate
inverse of hilbert matrix.
toeplitz(v) A test matrix that generates a matrix symmetrical along the diag-
onal. v is a vector.
1. 1. 1.
1. 1. 1.
1. 1. 1.
-->zeros(3,3)
ans =
0. 0. 0.
0. 0. 0.
0. 0. 0.
-->rand(1,3)
ans =
-->linspace(1,10,5)
ans =
-->logspace(1,10,5)
ans =
-->1:3:10 // increasing
ans =
1. 4. 7. 10.
-->10:-3:1 // decreasing
ans =
10. 7. 4. 1.
-->testmatrix(’magi’,3)
ans =
Scilab Quick Reference (Early Access) Chapter 1: Basics 35
8. 1. 6.
3. 5. 7.
4. 9. 2.
-->testmatrix(’frk’,3)
ans =
3. 2. 1.
2. 2. 1.
0. 1. 1.
-->testmatrix(’hilb’,3)
ans =
9. - 36. 30.
- 36. 192. - 180.
30. - 180. 180.
-->toeplitz([1,2,3,4])
ans =
1. 2. 3. 4.
2. 1. 2. 3.
3. 2. 1. 2.
4. 3. 2. 1.
End code
Kinds of matrices
Table 12 shows basic special types of matrices that stores different data type objects.
1. 2.
Command Description
list(a1,...) List of values of different types such as numbers, strings, or objects.
a1,... are scilab objects such as numbers, string, etc. Adding data
in a list can be one-by-one or in one batch. Empty parameters
create a list object with empty data.
struct(fn,fv,...) Values of different types (numbers, strings, or objects) are associ-
ated with a field name. fn is the field name and fv is the field
value. Adding fields in a struct can be one-by-one or in a single
call specifying the field name and field values in a respective order.
Empty parameter creates a struct object with empty fields.
tlist(f,a1,...) Same as list but a string type can be used to access an object
within the list. f as the field names, a1,... are scilab objects such
as numbers, string, etc. Similar to struct but differs on accessing
the fields and the values. Field names can be possibly accessed,
a vector which is the first parameter of the tlist. Note: First
fieldname is the name of the typed list and not included as field
name.
m(1)
1. 2.
m(2)
hello
-->g.sides = 4
g =
shapename: "square"
sides: 4
-->g.areequalsides = %t
g =
shapename: "square"
sides: 4
areequalsides: %t
Command Description
cell Matrix with different types. A special type of struct that has one
field named entries used for accessing values of a cell.
sparse Sparse matrix
full Convert sparse to full matrix including zero elements.
size Returns the size of the sparse matrix. Can be used in list and
matrices which output the dimension of the argument.
length Maximum of what size returns.
Table 13: Functions used for creating and manipulating a special matrix
-->t.str
ans =
hello
-->t.bool
ans =
T
End code
Table 13 shows other functions used to create and manipulate a special type of
matrix.
Sample Code
Start code
-->//create a sparse matrix
-->sp=sparse([1,2;4,5;3,10],[1,2,3])
sp =
( 4, 10) sparse matrix
Scilab Quick Reference (Early Access) Chapter 1: Basics 40
( 1, 2) 1.
( 3, 10) 3.
( 4, 5) 2.
-->size(sp)
ans =
4. 10.
-->length(sp)
ans =
10.
-->full(sp)
ans =
0. 1. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 3.
0. 0. 0. 0. 2. 0. 0. 0. 0. 0.
End code
Syntax
Sample Code
Start code
-->//default precision: format(10) - 8 significant figures
-->v=10.342341123
v =
10.342341
Scilab Quick Reference (Early Access) Chapter 1: Basics 41
Command Description
ceil(n) Round towards + inf. ceil(3.45) returns 4. ceil(-3.45) returns
-3.
factor(n) Returns prime factors of an integer in vector. verb—factor(45)—
returns [3, 3, 5].
fix(n) Round towards − inf. fix(3.45) returns 3. fix(-3.45) returns
-3.
round(n) Rounds to nearest integer. round(3.45) returns 3. round(-3.45)
returns -3. round(3.67) returns 4. round(-3.67) returns -4.
floor(n) Round towards 0. floor(3.45) returns 3. floor(-3.45) returns
-2.
int(n) Extracts the integer part. int(3.45) returns 3. int(-3.45) re-
turns -3.
primes(x) Returns the prime numbers between 2 and x in vector.
modulo(d,n) Remainder for d/n.
pmodulo(d,n) Positive remainder for d/n.
base2dec Conversion from base b to decimal base.
hex2dec Conversion from base 16 to decimal base.
oct2dec Conversion from base 8 to decimal base.
bin2dec Conversion from base 2 to decimal base.
dec2oct Conversion from base 10 to base 8.
dec2hex Conversion from base 10 to base 16.
dec2bin Conversion from base 10 to base 2.
sort Matrix sorting.
lex_sort Lexicographical sorting.
diff Cumulative difference between adjacent elements of a vector.
perms Permutation of a number.
permute Permute a given vector.
intersect Intersection of 2 vectors.
union Union of 2 vectors.
vectorfind Find vector.
rat Approximate rational expression.
binomial Binomial distribution.
Command Description
%eps Smallest number in scilab. Default value: 2.220D − 16 equivalent
to 2.220 ∗ 10−16
format(’t’,d) Where ’t’ can be ’v’, for variable, or ’e’, for scientific nota-
tion, and, d is the number of significant digits minus 2 (extra
digits). Other valid call: format(’v’) - default variable format,
format(’e’) - default scientific notation format, format(10) - (de-
fault format) formats ’v’ and ’e’ into 8 significant digits.
clean Rounds off very small number, value of %eps to zero.
-->a=1.23124,b=15.123125423
a =
1.23124
b =
15.123125
-->a,b
a =
1.231
b =
15.12
-->format(’v’)
-->a,b
a =
Scilab Quick Reference (Early Access) Chapter 1: Basics 43
1.23124
b =
15.123125
-->format(’e’)
-->a,b
a =
1.231D+00
b =
1.512D+01
End code
See printf function for more flexible and accurate formatting of output.
Syntax
A = poly(m,’s’<,’flag’>)
2 System matrix a term used in control systems
Scilab Quick Reference (Early Access) Chapter 1: Basics 44
m m can be a scalar or a matrix. If it is a scalar the result is s−m with s as the symbolic
variable. If it is a vector without a third argument (flag), then it is assumed as
roots of the polynomial, else if specified are coefficients. If it is a matrix the result
is |s ∗ I − m|, where I is an identity matrix with same dimension as m.
’s’ A string that stand as a symbolic variable used by the polynomial. It can be ’s’,
’x’, ’mypoly’, or any variable you like as long as it does not exceed 4 characters.
For the case of ’mypoly’, it is cut down to ’mypo’.
’flag’ Flag can be any of the two string: ’roots’(default) and ’coeff’. Use ’roots’ if the
given vector data are roots and use ’coeff’ if they are coefficients of the polynomial.
Sample Code
Start code
-->//Creating a symbolic variable
--> s = poly(0,’s’)
s =
s
--> s = %s // built-in variable: %s and %z
s =
s
-->//Using the symbolic variable in math
-->//operatorion to create a polynomial
--> p = 1+2*s+s*s
p =
2
1 + 2s + s
-->(s-1)*(s-2)*(s-3)*(s-4)
ans =
2 3 4
24 - 50s + 35s - 10s + s
End code
Scilab Quick Reference (Early Access) Chapter 1: Basics 45
Sample Code
Start code
-->//same as poly([1 2 3 4],’s’) with ’roots’ by default as flag
-->poly([1 2 3 4],’s’,’roots’)
ans =
2 3 4
24 - 50s + 35s - 10s + s
End code
Sample Code
Start code
-->poly([1 2 3 4],’s’,’coeff’)
ans =
2 3
1 + 2s + 3s + 4s
End code
Polynomial operation
Only one variable is allowed. Error if operation consists of 2 different variables. Table
16 where p1 and p2 are polynomials and n is a number which can be a scalar or a matrix.
Polynomial manipulation
Command Description
p1+p2 Adds two polynomials.
p1-p2 Subtracts p2 from p1.
p1*p2 Multiply two polynomials and expand.
p2/p1 Divide two polynomials and simplify.
p1\p2 Back-division or reverse division.
p1^n Exponent must be a number and not a polynomial.
Command Description
roots(p) Solve for the roots of a polynomial. Where p is a polynomial.
coeff(p) Extracts the coefficients of a polynomial starting from the constant.
Where p is a polynomial.
numer(p) Extracts the numerator of a rational polynomial. Where p is a
polynomial.
denom(p) Extracts the denominator of a rational polynomial. Where p is a
polynomial.
degree(p) Degree of the polynomial or the highest order of the polynomial.
Where p is a polynomial.
pol2str(p) Polynomial to string conversion. Where p is a polynomial.
eval(pol2str(p)) Evaluates a polynomial with the current value of the variable used
by the polynomial. Error if variable is not in the workspace.. p is
a polynomial.
p($:-1:1) Reverses polynomial coefficients.
varn(p,newvar) Change the variable used in the polynomial. Where p a polynomial
and newvar is a character string type.
-->p=poly([1 2 3 4],’s’,’coeff’)
p =
2 3
1 + 2s + 3s + 4s
-->varn(p,’x’)
ans =
2 3
1 + 2x + 3x + 4x
End code
Preparing a function to be evaluated later is declared in string form. Then using eval
to evaluate the function using the variables available in the workspace. For multiple
variable function, make sure to create all variables in the workspace. Error if there are
variables undeclared in the workspace.
The function can also be evaluated in a piecewise manner by defining the function
as scilab function then use feval to evaluate the function to a given value.
Sample Code
Start code
-->f = ’sin(t)+exp(-t)’; // declaring a function in string
-->t = 1; // create a variable t and assign a value
-->eval(f) // evaluate the function applying the value of t
ans =
1.2093504
-->sin(1) + exp(-1) // checking the answer
ans =
1.2093504
Scilab Quick Reference (Early Access) Chapter 1: Basics 48
-->deff(’[z]=f(x,y)’,’z=x^2+y^2’);
-->feval(1:10,1:5,f)
ans =
Complex construction
√
Treating %i as variable with value equal to −1 and use it makes the number be-
comes a complex.
Sample Code
Start code
--> a = 3+4*%i
A =
3 + 4i
End code
Scilab Quick Reference (Early Access) Chapter 1: Basics 49
Command Description
complex(a,b) Create a complex number where a is the real part and b the imag-
inary part. a and b can be a matrix to create a complex matrix.
Both matrix should have the same dimension. This avoids affixing
of %i.
abs(z) Magnitude of a complex number.
real(z) Real part of a complex.
imag(z) Imaginary part of a complex.
conj(z) Conjugate of a complex.
inv(z) Inverse of a complex.
[r,theta]= r as magnitude, theta as angle in radians.
polar(a+b*%i) theta can also be computed as atan(imag(z),real(z)).
Complex operation
Keywords: +, -, *, /, \, ^
Sample Code
Start code
--> a = 3+4*%i, b = 5+12*%i
a =
3 + 4i
b =
5 + 12i
--> a*b //complex multiplication
ans =
-33. + 56.i
End code
Complex manipulation
Command Description
zmat’ Transposes a complex matrix, zmat, and applying conjugate at the
same time.
Sample Code
Start code
--> a = 3+4*%i; // same as a = complex(3,4)
--> abs(a)
ans =
5
End code
Complex matrix
Keywords: ’
Matrix operation and some math operations in real numbers are still applicable in
complex matrix except transpose of a complex matrix. Table 19 shows the behavior of
complex matrix transpose.
Sample Code
Start code
-->zmat = int(rand(2,3)*10+1)+12*%i
zmat =
-->zmat’
ans =
3. - 12.i 3. - 12.i
9. - 12.i 7. - 12.i
4. - 12.i 10. - 12.i
Scilab Quick Reference (Early Access) Chapter 1: Basics 51
Command Description
plot(x, Plot x vs. y1, x vs. y2, and so on
[y1,y2,...,yn]) overlaying each plot. x, y1, y2, . . . , yn must be a column vector. For
row vector, use matrix transpose to transform to column vector.
xgrid Adds a horizontal and vertical grid to the plot.
xtitle( Adds xlabel, ylabel and title to the plot.
’t’,’x’,’y’) ’t’ as title of the plot, ’x’ as label of x-axis, ’y’ as label of y-axis.
End code
Plot can be customized after generating it such as changing the properties of the
axes, ticks, tick label, title, line color, line style, etc. There are commands used to
customized such properties but in this chapter we will be using the graphical axes
properties editor. Axes editor window can be accessed through the menu provided by
graphics window. Figures 8 and 9 shows screenshots of axes property editor.
Sample Code
Start code
1 -->x=[0:0.01:2*%pi];
2 -->y=sin(x)+cos(x);
3 -->plot(x,y,’k-’)
Scilab Quick Reference (Early Access) Chapter 1: Basics 52
4 -->xgrid
5 -->xtitle(’y=sin(x)+cos(x)’,’x’,’y’)
End code
Line 1 Creates a vector starting from 0 to 2π with 0.01 interval then store to variable
x.
Line 2 Create a set of values for a given function, y = sin x + cos x, that substitutes
each element of x.
Line 3 Call plot function of scilab to draw a plot with x as horizontal parameter and
y as vertical parameter. The third argument is a custom property of the graph, k
for black color, - for solid lines connecting the points.
Line 4 Adds horizontal and vertical grids to the plot.
Line 5 Adds a label to x, y and the title of the plot.
Output
1.17 Exercises
1. Matrix manipulation
(a) Construct a matrix of random integers between 1 and 10 with dimension 4×5,
i.e. 4 rows and 5 columns.
(b) Delete the 5th column to create a square matrix.
(c) Find the indices and values of elements less than 5.
(d) Replace all elements less than 5 by 0.
(e) Create a second matrix with 4 × 2 dimension.
(f) Apply matrix multiplication that avoids error and store result to c.
(g) Flip matrix c horizontally, i.e. rearrange the column in reverse order such that
the last column becomes the first column, and so on. Hint: use transpose and
submatrix extraction whichever is applicable.
2. Complex matrix manipulation
(a) Create a complex number where real and imaginary part are integers that are
randomly generated between 10 and 20.
(b) Create a 4 × 3 matrix of complex values where real and imaginary part are
random integers between 10 and 20.
(c) Insert the following column vector to the last column to make the matrix a
square
3 − 4i
5 − 12i
2 − 10i
−1 − i
(d) Locate the complex elements with real part greater than or equal to 15. Dis-
play the real values that satisfies the condition.
(e) Locate the complex elements with imaginary part greater than or equal to 17.
Display the imaginary values that satisfies the condition.
(f) Compute the magnitude of each element.
(g) Locate the complex elements with magnitude greater than or equal to 23.
Display the magnitude values that satisfies the condition.
Scilab Quick Reference (Early Access) Chapter 1: Basics 56
(h) Rotate the original 4 × 3 complex matrix by 180 degrees. Hint: use transpose
and submatrix extraction whichever is applicable.
3. Polynomial matrix manipulation
(a) Create a polynomial with degree equal to 5 and coefficients are integers that
are randomly generated between -50 and +50. Hint: use (−1)n where n is
random number from 1 to any positive integer to randomly generate a negative
number.
(b) Create a polynomial matrix where each element follows the same criteria as
above.
(c) Search for elements whose roots are all integer, all complex, all positive inte-
gers, and all negative integers.
4. Plotting
(a) Plot the following data:
{[5, 12], [2, 10], [0, 3], [5, 1], [8, −1], [9, 10], [−1, 5], [3, 9]}
(b) Plot the function below at t values between [-5,0] with 100 points linearly
spaced.
f = e−t − t − 10
df = −e−t − 1
Chapter 2
Programming Basics
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 58
2 Programming Basics
2.1 Objectives
• To know the basic construct of a function in scilab.
• To know how to load and execute a function.
• To know how to use nested function.
• To know how to manipulate input and output arguments as well as variable argu-
ments both input and output.
• To know how to create a script.
• To know how to read and write data to a file.
• To know how to read input from the user.
• To know how to display data with formatted output to the screen.
• To differentiate functions from scripts.
• To create an inline function using deff command that behaves like an external
function.
• To iterate values of a matrix through a loop such as for and while loop.
• To handle error and exceptions in scilab statements.
• To determine the significance of a nested for loop.
• To know how to break inner loop or outer loop using break command.
• To know how to skip statements within a loop using continue command.
2.3 Introduction
Programming a function or a script can be external or inline. External means
creating an external file that will be loaded to Scilab workspace for execution. Inline
function are constructed and executed directly in a console without creating external
file.
Scipad’ on the leftmost area, and the last option is to type edit.. The last option, i.e.
edit, is useful when you are writing a function because it opens the scipad editor with
code template of a function and saved with untitled.sci filename. You can also specify
name of the function to do such just call edit(’myfun’), opens the scipad editor with
function name myfun and saved in myfun.sci.
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 61
2.5 Scripts
Usage
Process a list of statements as a single batch. After the script is executed, all
variables inside the script are available in the workspace. Consuming extra memory
space for unncessary variables. Filename for scripts ends with .sce extension.
Syntax
<stmt1>
<stmt2>
<stmt3>
...
Replace <stmt1>, <stmt2>, <stmt3> by a valid scilab statements.
Sample Code
Start code
// create a test matrix of random numbers between
// 1 and 10
A = int(rand(3,3)*10+1);
// determinant of a matrix
detA = det(A);
// Eigen polynomial of matrix A
eigenpolyA = poly(A,’s’);
End code
3. Save the file with .sce extension, say, test script.sce. Any filename will do but
choose for a descriptive filename.
4. Load the script by clicking menu Execute >> Load into Scilab menu item under
the scilab editor. You may use exec(’test_script.exe’). Prior to that is to
change the current working directory of the console using cd command. Keyboard
shortcuts: ctrl+l.
5. Check the console. The output is shown below.
Start code
-->A,detA,eigenpolyA
A =
1. 8. 3.
6. 2. 3.
7. 6. 3.
detA =
78.
eigenpolyA =
2 3
- 78 - 76s - 6s + s
End code
2.6 Functions
Introduction
Function consists of scripts that are surrounded by a function block. In Scilab, input
and output arguments are specified. Arguments can be fixed or dynamic. Dynamic
arguments, also called variable arguments, will be discussed on the later section.
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 63
Usage
A function process list of statements that receives input arguments and the result is
stored into the output arguments. Variables inside the function are localized inside the
function block. After execution, only the output variables exist in the workspace. This
saves memory space eliminating unncessary variables. Filename for functions ends with
.sci extension.
Syntax
Sample Code
Start code
function f = factorial(x)
// calling built-in gamma function, x!
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 64
f = gamma(x+1);
endfunction
End code
Note: Text after // are comment lines and are ignored by Scilab.
Usage
Useful if there are repetitive simple task and creating a new external file is not
practical. Nested function can be located anywhere inside the main function and can
be accessed after the declaration.
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 65
Sample Code
Usage
Almost same concept with nested function but other functions are outside the main
function. This makes outside function possible to be declared in any order. Main
function is the one with the same name as the filename. Note: Variables inside the
function is not available and cannot be called within the other function.
Sample Code
function f=factorial(x)
f=gamma(x+1);
endfunction
End code
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 66
fun_internal.sce
<use factorial function here>
function f=factorial(x)
f=gamma(x+1);
endfunction
fun_external.sce
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 67
cd c:\\scilab\\mixed\\factorial.sci
exec(’factorial.sci’)
<use factorial function here>
End code
Usage
Function that can be created and loaded directly inline to the console without saving
into an external file.
Syntax
Sample Code
Start code
deff(’[x]=myplus(y,z)’,[’x=y+z’])
End code
Usage
if-elseif-else-end
Syntax
if condition
statements;
<elseif condition
statements;>
<else
statements;>
end
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 69
Sample Code
Start code
grade = 85;
if grade>=90 & grade<=100
disp(’Excellent’)
elseif grade>=80 & grade<90
disp(’Very good’)
elseif grade>=70 & grade<=80
disp(’Good’)
else
disp(’Study more’)
end
End code
Output
Very good
select-case-else-end
Same concept with if-else, selecting which statements are to be executed depending
which case the value equals to.
Syntax
select value
case case1
statements;
case case2
statements;
case case3
statements;
case case4
statements;
<else>
statements;
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 70
Sample Code
Start code
month = 8
select month
case 1
disp ’January has 31 days.’
case 2
disp ’February has 28 days, except in leap year, 29 days.’
case 3
disp ’March has 31 days.’
case 4
disp ’April has 30 days.’
case 5
disp ’May has 31 days.’
case 6
disp ’June has 30 days.’
case 7
disp ’July has 31 days.’
case 8
disp ’August has 31 days.’
case 9
disp ’September has 30 days.’
case 10
disp ’October has 31 days.’
case 11
disp ’November has 30 days.’
case 12
disp ’December has 31 days.’
else
disp ’No month associated.’
end
End code
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 71
Output
month =
8.
Usage
Syntax
Sample Code
Start code
//test_for.sce
a = [4,5,1,6];
for k = 1:length(a)
a(k) = a(k) + 1;
end
End code
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 72
Output
-->a
a =
5. 6. 2. 7.
while-loop
Usage
Syntax
while condition
statements;
end
Sample Code
Start code
i = 1;
while i<=5
//additional statements here
i = i+1; //update i
end
End code
Usage
Cases
Case 1 for-for
Case 2 while-for
while cond
stmt1;
for var2 = vector_expr
stmt2;
stmt3;
end
stmt4;
end
Case 3 for-while
Case 4 while-while
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 74
Command Description
break Used in exiting the loop, without executing the remaining state-
ments, when specified condition is met. Cannot break outer loop
in nested loops.
continue Used in skipping statements inside the loop when specified condi-
tion is met.Cannot break outer loop in nested loops.
while cond1
stmt1;
while cond2
stmt2;
stmt3;
end
stmt4;
end
Can be placed anywhere inside a loop. Table 21 shows how to use break and
continue command.
Sample Code
Start code
for k=1:10
if k==5 //skip k=5
continue;
end
disp(k)
if(k>=7) //stop if k=7 is reached
break;
end
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 75
Command Description
varargin Storage for variable number of input. Must be the last argument.
varargout Storage for variable number of output. Must be the last argument.
[out,in]=argn Counts the number of arguments, input
or and output. Result in vector form with first
outin=argn element as number of output and second element as number of
input.out counts the number of output arguments.in counts the
number of input arguments. For 1 output, outin, outint(1)=out
& outint(2)=in.
end
End code
Output
1.
2.
3.
4.
6.
7.
Variable argument list makes the function more flexible and dynamic as shown in
table 22.
Syntax
Cases
Sample Code
Start code
//Main function
function [o1,o2,o3,o4] = varargcases(x)
o1 = case1(x,2*x,3*x); // 18
[o2a,o2b,o2c] = case2(x);
o2 = [o2a,o2b,o2c]; // [3, 6, 9]
[o3a,o3b] = case3(x,2*x,3*x,4*x);
o3 = [o3a,o3b]; // [30, 60]
[o4a,o4b,o4c,o4d] = case4(x,x,x,x,x); // [1, 2, 15, 30]
o4 = [o4a,o4b,o4c,o4d];
endfunction
b1 = 0;
for k = 1:in_count
b1 = b1 + varargin(k);
end
endfunction
for k = 1:out_count
varargout(k) = x*k;
end
endfunction
in_sum = 0;
for j = 1:in_count
in_sum = in_sum + varargin(j);
end
for k = 1:out_count
varargout(k) = k*in_sum;
end
endfunction
in_sum = i1;
for j = 1:in_count-1
in_sum = in_sum + varargin(j);
end
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 78
Command Description
input Reads input from the console.
disp Display the value to the screen without its variable name.
disp(value1<,’name1’<...>>)
o4a = 1;
o4b = 2;
for k = 1:out_count-2
varargout(k) = k*in_sum;
end
endfunction
End code
This can be useful if you want to ask user for an input. Displaying the values is
by default can be done by putting a semicolon at the last statement. But formatted
displaying of output can also be done and is considered flexible and preffered by some
of the programmers to control the appearance of the data to be displayed. Table 23
shows the syntax.
Sample Code
Start code
-->n = input(’Enter number’)
Enter number: 5
n =
5.
Command Description
printf Prints the formatted output to the console.
printf(’format’, val1, ..., valn)
sprintf Returns the formatted output as string.
sprintf(’format’, val1, ..., valn)
n =
a string must be enclosed with quotation
Formatting output in a tabular form is oftenly used. Table 24 shows the command.
Format
Placeholder Description
d Integer placeholder
e Scientific notation placeholder.
f Floating-point placeholder.
g Chooses between %f and %e. Whichever has the shortest format.
s String placeholder.
c Character placeholder.
Placeholder
Sample Code
Start code
-->//format left-aligned, with padding of 10
-->//characters and with fixed 4 decimal places
-->printf("%-10.4f",12.41212532)
12.4121
-->s = sprintf("%-10.4f",12.41212532)
s =
12.4121
End code
Saving to an file is useful for external storage of commands and data. Also, can be
used for logging purposes. Table 26 shows reading of data from external file.
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 81
Command Description
fscanf Read data from a file.
[out1,...,outn]=
fscanf(’file’,’format’,var1,...,varn)
fprintf Output data to a file.
fprintf(’file’,’format’,var1,...,varn)
diary(filename) Save current command from console to a filename. To stop saving
to the file use diary(0) or open another diary with a new filename.
Be careful of opening an existing file because the data inside will
be lost if you do so.
save Save current result from console to a file in *.dat format.
load Load *.dat file into scilab workspace as matrix data.
file Manage accessing of external file.
pwd Print working directory.
Sample Code
Start code
-->//print the current working directory
-->pwd
ans =
C:\
-->diary(’scilab_diary.txt’)
-->a=1
a =
1.
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 82
-->hello
!--error 4
Undefined variable: hello
-->g=int(rand(3,3)*10+2)
g =
2. 9. 4.
7. 3. 4.
8. 7. 4.
-->diary(0)
-->not_recorded=’not in the text file’
not_recorded =
not in the text file
End code
scilab_diary.txt
-->a=1
a =
1.
-->hello
!--error 4
Undefined variable: hello
-->g=int(rand(3,3)*10+2)
g =
2. 9. 4.
7. 3. 4.
8. 7. 4.
-->diary(0)
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 83
Command Description
lasterror Get last recorded error message.
errcatch Set a trap for a specified error and perform an action.
error Issue an error with specified number and error message.
errclear Clears the action of an error handler of type n if a error number is
specified, otherwise, clears all error.
iserror Returns 1 if error occurs, and 0 otherwise.
Usage
Handling exceptions make the program robust without stopping program executon.
Such exceptions like limiting input to a numeric character, warning message for out-of-
bounds accessing of element in a matrix, and other user specified criteria, error reading a
file or the file does not exist. To view the tabular list of errors, type help error_table.
Table 27 shows command to handle errors.
Syntax
try
statements;
catch
[error_str,n,line,fname]=lasterror(<flag>)
end
Sample Code
Start code
try
b = eyes(3,3)
catch
[s,n,line,fname]=lasterror()
end
End code
Output
fname =
line =
0.
n =
4.
s =
Regular Expression
Table 30 shows the basic syntax of regular expression. Same syntax with Perl regular
expression.
Syntax
[start<,end<,token>>]=regexp(str,pattern<,’o’>)
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 85
Command Description
string Converts other type to string type. After converting try to check
the type by issuing the command typeof with variable as argu-
ment.
strtod Convert string to double.
strcmp String compare.
length Number of characters in a string.
ascii Ascii equivalent in string form.
grep Find string from list of strings.
strrev Reverses a string.
part Extracting substring.
strtok Tokenize or split strings based on a given delimiter.
strindex Searches a position of character(s) in a string.
isalphanum Check if string is an alphanumeric character.
isascii Check if string is an ascii character.
isdigit Check if string is a digit.
isletter Check if string is a letter.
isnum Check if string is a numeric.
Command Description
evstr(str_array) Evaluate array of statements enclosed in string.
eval(str_array) (Alternative of evstr) Evaluate array of statements enclosed in
string.
exectr(instr) Execute a scilab instructions enclosed in string format. Instructions
are arrays of string statements separated by semicolon.
Command Description
regexp Finding a substring that matches the regular expression.
where
str String input to search.
pattern Pattern of substring to locate.
’o’ Optional input parameter for locating substring once.
start Start index position of substring in a larger string.
end End index position of substring in a larger string.
token The text of each string that matches the pattern.
Start code
-->[a b c] = regexp(’this is a not-so-long string’,’/this/’)
c =
this
b =
4.
a =
1.
End code
2.23 Exercises
1. Function, varargin, sprintf, printf, error handling
(a) Create a function that formats a floating-point number to a specified decimal
precision. The function receives two numbers, a floating-point and an integer
and outputs a string formatted number. Use sprintf function, and try-catch
to catch errors.
Scilab Quick Reference (Early Access)
Chapter 2: Programming Basics 87
Command Description
calendar Shows the current month calendar.
clock Shows the current date and time. Format:
[year, month, day, hour, min, sec].
date Current date showing day, month, and year.
datenum Current date in long number type.
datevec(t) Convert date in long format to date format
[yr, mo, day, hr, min, sec]. Sample: datevec(731129) returns
[2001.10.5.0.0.0.] which means October 5, 2001 with zero hour,
zero min and zero seconds.
eomday(y,m) End of month day, returns the last day of the month of a given
year. Used to query how many days in a month of a given year.
etime([t2],[t1] Elapsed time.
getdate Return current date and time information.
now Returns the current time and date in long format.
realtime(t) Set date origin if called once. Successive call waits till the the
argument time, t is reached.
realtimeinit Set time unit. Used side-by-side by realtime.
sleep(t) Suspend Scilab execution in t milliseconds.
tic Start stopwatch timer.
timer CPU time since preceding call of timer function.
toc Stop stopwatch timer and return the elapsed time starting from
calling tic.
weekday(t) Return day of the week given t milliseconds.
Command Description
pause Interrupts evaluation of a function. Useful for debugging purposes
which check for variables used inside the function. Level of inter-
ruption is indicated by -n-> where n is the level.
abort Used to exit pause mode and return to standard level prompt, i.e.,
from -n-> to -->.
[w1]=return(f1) Same function as resume but returns a variable from within
the function to be loaded to the workspace. w1 is a
copy of variable f1 from function which is loaded into the
workspace. Variable to be copied can be extended to any num-
ber, [w1,w2,...]=return(f1,f2,...).
quit Exit Scilab.
resume Interrupt pause mode and resume to next lower pause level, i.e.,
from -n-> to -(n-1)->.
lines Paging of Scilab output showing the number of vertical lines and
columns to display before giving a prompt to continue display.
Valid syntax: lines - shows the current paging setting, lines(0)
- disable vertical line paging, lines(r) - sets number of lines to
display to r, lines(r,c) - sets number of lines to r and columns
to c.
clc Clear the console display deleting previous commands from the
console but not from the history.
tohome Clear the console display but does not delete the previous com-
mands issued by the user. Can still use the scroll bar to browse
previouse command.
editvar(’var’) Edit a variable var. Display a tabular editor for matrix type vari-
able.
(b) Create a function that outputs data in tabular form. The function receives
a variable input in pairs specifying the column name and the array of data.
Number of columns vary depending on the input. No output to return but
just display a tabular form. Note: Do not format the data leave its format
the way it is given. Mind the alignment of each column where column width
depends on the longest character. Use try-catch to catch errors.
2. Scripts, inline function, string, regex
Use try-catch to catch errors.
(a) Create a script that extracts all numbers in a given string equation.
(b) Create a script that extracts all variables in a given string equation.
(c) Create a script that extracts the constant of the equation in a given string
equation.
(d) Create a script that extract the coefficient matrix, constant matrix, and the
variables used. Your script must query for the number of equations and input
from user the equations in string format and save it in a string array. Inside
your script are an 3 different inline functions that extract coefficients, extract
variables and extract constant.
Chapter 3
Plotting
Scilab Quick Reference (Early Access) Chapter 3: Plotting 91
3 Plotting Basics
3.1 Objectives
• To know how to create a 2D plot from a given data or function.
• To learn how to customize plot properties.
• To know how to divide a graphics window to contain multiple plot.
• To know what are other plotting capabilities for Scilab.
• To know how to animate plotting in Scilab.
3.3 Introduction
Plotting, also known as charting, is very handy in Scilab as well as animating the
plot. There are a lot of plotting function but we will select only those basic function.
Usage
Basic plotting involves 2 basic Scilab function, plot and plot2d. plot has an
advantage of being the same syntax with Matlab plot, that is if you are planning to
use Matlab. While plo2d syntax is limited to Scilab only and other open-source math
software but it is flexible compared to plot function.
plot
Syntax
plot(x,y[,’scm’])
Sample Code
Start code
Scilab Quick Reference (Early Access) Chapter 3: Plotting 93
plot([1:5],2*[1:5],’k-*’)
End code
Output
3.5 plot2d
Syntax
plot2d(<x>,y<,prop1=value1,prop2=value2,...>)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 94
Sample Code
Start code
-->clf
-->//using 3 dots to continue command to next line
-->plot2d(-1:5,sin(-1:5),...
-->leg=’this is a caption’,...
-->style=3,...
-->axesflag=5)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 95
End code
Output
plot2dx series
Command Description
plot2d1 Plot a curve with logarithmic scale.
plot2d2 Plot a curve as step function.
plot2d3 Plot a curve with vertical bars.
plot2d4 Plot a curve with arrows.
Plotting a function is best done when defined first then use fplot2d command to
plot it in a piecewise manner. Sample code is given below. The output displays a plot
like a mountain with smooth line interconnections.
Sample Code
Start code
-->deff("[y]=f(x)","y=sin(x)+cos(x)")
-->x=[0:0.1:10]*%pi/10;
-->fplot2d(x,f)
End code
Table 36 shows some commands used to customize grids and axes ticks.
Sample Code
Start code
-->//using the figure generated by the previous code
-->//getting the handle of the current figure
Scilab Quick Reference (Early Access) Chapter 3: Plotting 97
Command Description
xgrid(<n>) Add x and y grid to the graph drawn in imaginary lines. To change
the color of the grid just specify the value of n.
h=get(prop) Properties such as ’current_figure’ and ’current_axes’. Store
the handle to a variable and the properties will be displayed. You
can set the property of figure or axes through dot operator.
set(prop,val) Setting the property of the figure or the axes. Value will be dis-
played when storing the handle of figure or axes to a variable.
delete(h) Delete or remove an entity such as the figure, axes, children of
figure or axes, or a callback with argument h as its handle.
drawaxis(opt) Manually change the orientation of the axis in the graphics window.
opt are properties such as x,y,dir,sub_int,fontsize,format_n,
seg,textcolor,ticscolor,tics.
copy(h) Copy a graphic entity with handle h.
replot(vec) vec is a vector with 4 values designated as x-axis and y-axis bound-
aries.
-->f = get(’current_figure’)
f =
visible = "on"
rotation_style = "unary"
event_handler = ""
event_handler_enable = "off"
user_data = []
tag = ""
-->//getting the handle of the current axes of the figure above
-->a = get(’current_axes’)
a =
visible = "on"
axes_visible = ["on","on","on"]
axes_reverse = ["off","off","off"]
grid = [-1,-1]
x_location = "origin"
y_location = "origin"
title: "Label"
x_label: "Label"
y_label: "Label"
z_label: "Label"
auto_ticks = ["on","on","on"]
x_ticks.locations = [-1;0;1;2;3;4;5]
y_ticks.locations = matrix 11x1
z_ticks.locations = []
x_ticks.labels = ["-1";"0";"1";"2";"3";"4";"5"]
y_ticks.labels = matrix 11x1
z_ticks.labels = []
box = "on"
filled = "on"
sub_ticks = [3,1]
font_style = 6
Scilab Quick Reference (Early Access) Chapter 3: Plotting 99
font_size = 1
font_color = -1
fractional_font = "off"
isoview = "off"
cube_scaling = "off"
view = "2d"
rotation_angles = [0,270]
log_flags = "nnn"
tight_limits = "off"
data_bounds = [-1,-0.9589243;5,0.9092974]
zoom_box = []
margins = [0.125,0.125,0.125,0.125]
axes_bounds = [0,0,1,1]
auto_clear = "off"
auto_scale = "on"
hidden_axis_color = 4
hiddencolor = 4
line_mode = "on"
line_style = 0
thickness = 1
mark_mode = "off"
mark_style = 0
mark_size_unit = "tabulated"
mark_size = 0
mark_foreground = -1
mark_background = -2
foreground = -1
background = -2
arc_drawing_method = "lines"
clip_state = "clipgrf"
clip_box = []
user_data = []
-->//a.parent is the same as get(’current_figure’)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 100
Command Description
xtitle(’title’) Adds title to the plot shown at the center top of
the plot. To add label on x-axis and y-axis use
xtitle(’title’,’x-label’,’y-label’<,boxed=1>) where
boxed optional property surround the label with a box.
title(’title’) More styles in setting the title of the plot. Styles are
backgroundcolor, color, edgecolor, fontname, fontsize,
position, rotation, visible.
Command Description
legend(h,’leg1’) Add legend to the plot of figure with handle h, ’leg1’ is the name
of the plot. Specify another string if there are multiple plots. Is-
sues error if the number of plot is less than the number of string
argument.
caption Add a string to the plot specifying a defined location. Syntax:
leg = caption(p,’str’,location) returns a legend handle.
End code
Table 37 shows some command to add title and label to the plot.
Usage
Legend and caption
Usage
Table 38 shows command how to add legend and captions to the plot.
Command Description
subplot(rci) Divides the plot into a matrix of plot. r for row, c for column, and
i for index to place the next plot. Index positioning starts from
topmost-left going to right then down to the bottom.
Sample Code
Start code
subplot(221)
plot2d()
subplot(222)
plot3d()
subplot(2,2,3)
param3d()
subplot(2,2,4)
hist3d()
End code
Output
Sample Code
Start code
-->plot2d
-->xstring(1,-1.5,’string’)
-->xstring(1,-1.5,’string90’,90)
-->xstring(1,-1.5,’stringM90’,-90)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 103
Command Description
xstring xstring(x,y,’string’<angle<,boxed>>). x and y are coordi-
nates of lower-left point of the string based on the ticks specified
by the graph. ’string’ is the string of characters to display on
the graph. angle is the angle of inclination of the string in degrees.
boxed is either 1 or 0, 1 for drawing a frame around the string and
0 (default) for no frame around. Boxed string is possible if angle
is zero.
xstringb Draw a string in a box.
xstringl Computes the box that surrounds the string.
stringbox Compute the bounding rectangle of a text.
End code
Output
Figure 15 shows the sample output for adding string to the plot.
Command Description
locate(n) Used to point n coordinates from the plot through mouse click.
After the locate command is issued, the focus is transferred to
the plot.
xclick Wait for mouse button to be clicked. Mouse button captures left,
middle (if any) or right mouse click.
Command Description
draw(h) Called after drawlater. Draws a plot with argument graphic han-
dle of polyline.
drawlater Draw the plot later called by draw.
drawnow Called when showing the plot after drawlater and draw command.
Sample Code
Start code
subplot(212)
a=gca();
plot2d
drawlater
subplot(211)
plot2d1 // default drawing mode
e=gce();
draw(e.children(2)) // draw a single polyline of the second axes
e.children(1).visible=’off’; // We can choose to make a line invisible
draw(e) // draw Compound and its children <=> draw all the visible polylines
drawnow // ...now!
e.children(1).visible=’on’;
Scilab Quick Reference (Early Access) Chapter 3: Plotting 106
Command Description
gcf Get current figure. Returns the current figure. Same as
get(’current_figure’) command.
clf Clear current graphics window.
Command Description
paramfplot2d Animate the function plotting.
twinkle Blink the current polyline of the plot.
End code
Note: Code below is excerpted from the help sample code of Scilab.
Miscellaneous
Usage
Plot can be customized after generating it such as changing the properties of the
axes, ticks, tick label, title, line color, line style, etc. There are commands used to
customized such properties but in this chapter we will be using the graphical axes
properties editor. Axes editor window can be accessed through the menu provided by
graphics window. See figure 16 and 17.
Animating plot is useful when visualizing a certain chart and emphasizing a plot.
Animation gradually changes one of the parameter, commonly the amplitude. Table 44
shows how to add animation to the plot for emphasis.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 107
Sample Code
Start code
/*******************
* animate_plot.sce
*******************/
//function to animate
function y=f(x,t)
y = t*(exp(-x)-x-10);
endfunction
Command Description
polarplot Polar plot.
histplot Histogram plot.
bar Vertical bar plot.
barh Horizontal bar plot.
pie Pie chart.
errbar Error bar plot.
Command Description
Matplot Plot a matrix data by colors.
contour2d Level curves of a surface.
champ Plot the vector field with arrow direction.
grayplot Plot data by colors.
graypolarplot Plot data by colors in polar coordinates.
Output
The output above shows a graphics window with plot that changes gradually its
amplitude then draws blue line across y = 0 and blink the line for a few times.
Surface plotting
Command Description
xpoly Draw a polyline or a polygon
xpolys Draw a set of polylines or polygons
xrpoly Draw a regular polygon
xsegs Draw unconnected segments
xfpoly Fill a polygon
xfpolys Fill a set of polygons
Polygon plotting
//plot function
fplot2d([-3:0.1:1],f)
//draw horizontal line on x = 0
xpoly([-3,1],[0,0])
xi=[-2.5,0];
i=1;
maxIter = 5;
for k = 1:maxIter
fL = feval(xi(i,1),f);
fU = feval(xi(i,2),f);
plot(xi(i,1)*ones(1,2),[0, fL],’--g’)
plot(xi(i,2)*ones(1,2),[0, fU],’--g’)
// compute approx root, xr
xr(i) = (xi(i,1)+xi(i,2))/2;
fR = feval(xr(i),f);
Scilab Quick Reference (Early Access) Chapter 3: Plotting 111
plot(xr(i)*ones(1,2),[0, fR],’--r’)
if(i>1)
er(i) = abs((xr(i)-xr(i-1))/xr(i))*100;
else
er(i) = 100;//100%
end
//summary
x_mdialog(’xr’,string(1:length(xr)),string(xr))
x_mdialog(’er’,string(1:length(er)),string(er))
End code
3.11 Exercises
1. Plotting a digital pulse
Scilab Quick Reference (Early Access) Chapter 3: Plotting 112
(a) Plot the digital signal [1, 1, 0, 0, 1, 0, 1] in digital pulse which is a square pulse.
(b) Label x − axis with tick label in center between 2 ticks. Label y − axis tick,
and the title as ’Digital Signal’.
(c) Plot the following data in a stair plot.
x = [1, 2, 3, 4, 5]
y = [1, 2, 5, 3, 2]
2. Customizing plot
(a) Add string, legend, ticks, and grid for the plot in problem 1.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 113
3. Animating plot
(a) Animate the plot in problem 1.
4. Capturing mouse interaction
(a) Capture 3 points in the plot using mouse click.
5. Polygon plotting
(a) Create a pentagon with center at (3, 3). Create a nonagon with center at (3, 4)
and overlay the plot from the previous plot. Fill the intersection between two
polygons. Compute for the area of intersection.
Chapter 4
Dialogs
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 115
4 Dialogs
4.1 Objectives
• To use dialogs to visualize the resulting data.
• To emphasize given data used for calculation in a dialog.
4.3 Introduction
Dialogs are oftenly used to visualize a data temporarily. It is often used than full-
pledge GUI since it is easy to code. As easy as no assigning of dialog ID, callback
functions and other controls. Each dialog has its own usage. Table below lists the
dialogs available in Scilab excluding the obsolete functions.
Dialog boxes returns the result in string form. To convert string into number you
can use strtod to convert string to double, eval or evstr to evaluate the string as
Scilab command. Table 48 shows list of available dialog boxes in Scilab.
4.4 messagebox
Figure 19 shows the message box screenshots.
Syntax
[btn] = messagebox(msg<,title<,icon<,but_arr<,modal>>>>)
msg Message in string.
title Title of the dialog in string.
icon String that can be either: ’error’ | ’info’ | ’passwd’ | ’question’ | ’warning’|
’scilab’.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 116
4.5 progressionbar
Table 49 shows syntax for displaying progress bar window that shows progress of a
command. Figure 20 shows the pogress bar screenshots.
4.6 waitbar
Table 50 shows syntax for displaying progress bar window that shows progress of a
command with definite percentage of progress. Figure 21 shows the waitbar screenshots.
4.7 x dialog
Figure 22 shows the screenshots.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 117
Command Description
messagebox Display the message in a popup dialog.
progressionbar Display an indefinite progress bar.
waitbar Display an updated progress bar.
x_dialog Input dialog that accepts input and returns the value in string.
x_choices List of choices that uses toggle buttons for list of choices.
x_choose A list of string to choose. Double-click the item to select it.
x_choose_modeless A modeless dialog version of x_choose.
x_mdialog Input dialog arranged in matrix for multiple inputs.
x_matrix Similar to x_dialog but used for editing a matrix. If the type
of matrix is numeric, the return type is also numeric rather than
string.
Command Description
w=progressionbar(str) Displays the indefinite progress bar and returns the handle w.
This is used to initialize progress bar. str is a string such as
’Initializing...’.
progressionbar(w,str) Updates the string of the progress bar with handle w.
winclose(w) Closes the progress bar.
Command Description
w = waitbar(str) Displays the indefinite progress bar and returns the handle w.
This is used to initialize progress bar. str is a string such as
’Initializing...’.
waitbar(p,str,w) Updates the string of the progress bar with handle w specifying the
percentage p.
winclose(w) Closes the progress bar.
Syntax
r = x_dialog(prompt,default)
prompt A string that prompts for the user. Prompt can be multiline by using vectors
of string.
default Default value in string. Can be matrix to extend height of input textfield.
r Output results to [] if cancelled and returns the input in string.
4.8 x mdialog
Figure 23 shows the screenshots.
Syntax
rvec = x_mdialog(title,rowlabel,default_values)
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 119
rmat = x_mdialog(title,rowlabel,collabel,default_values)
title A string that prompts the user for input. Prompt can be multiline by using
vectors of string.
rowlabel Vector of row labels.
collabel Vector of column label.
default values It can be column vector for one column or a matrix if row and column
label are provided. Note: default values must be a string array. Use string to
convert numeric data to string type.
rvec Vector input data. Output results to [] if cancelled and returns the input in
string.
rmat Matrix input data. Output results to [] if cancelled and returns the input in
string.
4.9 x choices
Figure 24 shows the screenshots.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 120
Syntax
result = x_choices(title,list(list(lbl,default_int,choices)...
<,list(’lbl’,default_int,choices)<,...>>))
title A string that prompts the user for input. Prompt can be multiline by using
vectors of string.
list A Scilab keyword that creates a list.
lbl A string which is a label of its respective toogle choice list.
default int An integer value which is the index of the selected choice item.
choices A vector of toggle items in string type.
result A result in vector form for multiple choices which is in integer type specifying
the selected index of each choice.
4.10 x choose
A modal dialog that shows a list of items. Use x\_choose\_modeless to set the
popup dialog to non-modal, i.e., it does not block interacting the console while the
dialog appears. Figure 25 shows the screenshots.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 121
Syntax
choice = x_choose(item_vec,title<,button_text>)
item vec List of items in vector.
title A string that specifies the popup dialog title.
button text Text of the button below the list. Default value is ’Cancel’.
4.11 x matrix
Figure 26 shows the screenshots.
Syntax
m = x_matrix(prompt,init_mat)
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 122
//plot function
fplot2d([-3:0.1:1],f)
//draw horizontal line on x = 0
xpoly([-3,1],[0,0])
xi=[-2.5,0];
i=1;
maxIter = 5;
for k = 1:maxIter
fL = feval(xi(i,1),f);
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 123
fU = feval(xi(i,2),f);
plot(xi(i,1)*ones(1,2),[0, fL],’--g’)
plot(xi(i,2)*ones(1,2),[0, fU],’--g’)
// compute approx root, xr
xr(i) = (xi(i,1)+xi(i,2))/2;
fR = feval(xr(i),f);
plot(xr(i)*ones(1,2),[0, fR],’--r’)
if(i>1)
er(i) = abs((xr(i)-xr(i-1))/xr(i))*100;
else
er(i) = 100;//100%
end
//summary
x_mdialog(’xr’,string(1:length(xr)),string(xr))
x_mdialog(’er’,string(1:length(er)),string(er))
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 124
End code
Chapter 5
Graphical User Interface (GUI)
Scilab Quick Reference (Early Access) Chapter 5: GUI 126
5.3 Introduction
Graphical user interface is widely used to create an application that arranges visu-
alization in an orderly manner for more user-friendly application.
5.4 UI controls
Keywords: uicontrol
Table 51 shows different styles of UI controls.
5.6 UI properties
Table 53 and 54 shows properties of each UI control styles.
Scilab Quick Reference (Early Access) Chapter 5: GUI 127
Controls Description
text Static text used as label.
edit Editable text where user can input data.
slider Draggable sliders that changes its value and updates bar position.
pushbutton A button used for triggering events when clicked.
radiobutton A selection button that allows a single selection.
checkbox A selection box that allows multiple selection.
frame A boundary marker used to group related components.
listbox A list of data.
popupmenu A list of data that displays one data and the rest of the data are
accessible by cliking the drop down button.
Property Values
backgroundcolor Vector. [r, g, b] where r, g, b values are between [0, 1]
figure_name String.
foregroundcolor Vector in [r, g, b] values.
position Vector such as [x, y, width, height]
tag String.
userdata Vector.
Property Values
callback Callback function in string.
parent Handle of the parent container where the UI is being laid out.
position Contains the position and size of the control given in a vector such
as [x,y,w,h], with (x, y) as coordinates, w and h as width and
height respectively. Unit is in pixel.
relief Border style such as ’groove’ | ’sunken’ | ’raised’
string Label within the UI control.
style UI contol style such as ’edit’ | ’text’ |
tag Identifier of the UI control in string.
Property Values
backgroundcolor Background color of the figure or the UI control.
enable Set UI control to enable.
fontangle Set the font angle.
fontsize Set the font size.
fontunits Set the units of the font.
fontweight Set the fontweight.
fontname Set the fontname.
foregroundcolor Color of the font.
horizontalalignment Horizontal alignment of the text inside UI control.
listboxtop Set the listbox to be on the top.
max Sets the maximum values of a specific UI control such as slider.
min Sets the minimum values of a specific UI control such as slider.
path Sets the path of the UI control.
sliderstep Sets the sliderstep of the slider UI control.
units Sets the units to be used.
userdata Sets the global userdata value.
value Value of the UI control.
verticalalignment Vertical alignment of the text inside UI control.
visible Set visibility of UI control in the figure.
Property Values
gcbo Returns the handle of the calling object.
findobj(’tag’,’id’) Returns the handle of UI control with tag equals to id.
5.7 Layouting
Layouting Figure
Figure positioning has top-left corner as (x, y) starting coordinates and the reference
is at top-left corner of the screen.
Layouting UI controls
Uses absolute positioning where the origin, (0, 0), is located in the lower-left corner
of the graphics window.
Layouting Axes
a.axes_bounds = [1/4,0,2/3,1];
endfunction
// create a textfield UI
tf = uicontrol(’parent’,fh,...
’position’,[13,182,100,20],...
’string’,’text’,...
’tag’,’tfid’,...
’style’,’edit’,...
’backgroundcolor’,[1 1 1],...
’relief’,’groove’);
// create a button UI
but = uicontrol(’parent’,fh,...
’position’,[18,160,85,20],...
’string’,’plot’,...
’tag’,’bid’,...
’style’,’pushbutton’,...
’foregroundcolor’,[1 1 1],...
’callback’,’change_relief’);
Scilab Quick Reference (Early Access) Chapter 5: GUI 131
function change_relief()
set(gcbo,’relief’,’sunken’);
sleep(100);
set(gcbo,’relief’,’raised’);
str = get(findobj(’tag’,’tfid’),’string’);
messagebox(string(evstr(str)),’modal’);
f = gcf();
delete(f.children(1));
messagebox(’Deleted previous plot.’,’modal’);
drawaxes();
a = gca();
plot(a,evstr(str),evstr(str));
endfunction
End code