100% found this document useful (1 vote)
131 views173 pages

Scilab Basics - Control Systems For Maritime Professionals Book - 1 by Kalyan Chatterjea

Scilab Basics_ Control Systems for Maritime Professionals Book - 1 by Kalyan Chatterjea

Uploaded by

f
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
131 views173 pages

Scilab Basics - Control Systems For Maritime Professionals Book - 1 by Kalyan Chatterjea

Scilab Basics_ Control Systems for Maritime Professionals Book - 1 by Kalyan Chatterjea

Uploaded by

f
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Scilab Basics

Control Systems For Maritime Professionals – Book


1
By

Kalyan Chatterjea, FIMarEST


Extra First Class Engineer (Motor & Steam), South Shields
MSc in Systems, Controls & Information Technology (Sheffield)
Master of Education (Sheffield)
Previously Taught at:
Singapore Maritime Academy
Malaysian Maritime Academy
Emas Academy, Singapore
Wavelink Maritime Institute, Singapore
Copyright © 2020 Kalyan Chatterjea
Companion Website for Competency Monitoring
II. Series Content
1. Scilab Basics

2. Control System Fundamentals

3. Modelling Control Systems

4. Time and Frequency Domain Analysis

5. Transfer Functions

6. PID Control & Tuning

7. Control System Stability

8. Introduction to State-Space Method

9. Maritime Examples

10. Control Applications on Arduino Uno


III Series Introduction
Shipboard Control regulates all systems on deck and engine. Like shore-
based power plants, accurate controls of level, temperature, pressure, flow,
speed, etc. in shipboard systems are important in various marine
applications.

This series on control system emphasises understanding and analysis of basic


control theories. An industry-level software, Scilab, and application of
simulation techniques using XCOS (“Open Source | Www.Scilab.Org” n.d.)
to visualise control processes, are amply used in the text for better
comprehension and evaluation of what-if scenarios.

The series ‘Control Systems for Maritime Professionals’ is divided into ten
parts. Each part is published as an individual book. Each part has several
Sections and these Sections have measurable learning objectives, which are
outlined at the beginning of each Section. A companion website (Companion
Website for Competency Monitoring) is created for formative learning of the
content in the books.
IV Acknowledgment
I am thankful to the open-source communities, without which this series of
books will not be possible. This Book-I of the series is developed using open-
source software exclusively. I acknowledge using the following software:

LibreOffice
Sigil
Calibre
Scilab
Various Linux Distributions - Peppermint Linux, Ubuntu, Linux
Mint, MX Linux
Gimp
Inkscape
Zotero
Dropbox
Bluefish
htmlTidy
Grammarly
Google

These wonderful programs are created by the thankless efforts of many


passionate and dedicated developers. I am grateful for their invaluable
services.

The main inspirations for the book came after reading "Introduction to Scilab
- Application to Feedback Control", 2014, by Yassin Ariba of Brno
University of Technology, and "Feedback Control with Scilab and Arduino",
2016, by Varodom Toochinda of Kasetsart University. I am deeply indebted
to them. These two references serve as the main resources for this
publication.

Also, I need to thank Kindle Direct Publishing (https://kdp.amazon.com/) for


allowing me to publish this book.

Kalyan Chatterjea
Singapore
May 2020
V Table of Contents
I. Title Page
II. Series Contents
III. Series Introduction
IV. Acknowledgment
V. Table of Contents
VI. List of Figures

1. Scilab Basics - Introduction


2. Who This Book is intended for
3. Scilab Installation
4. Scilab Environment
5. Scilab as a Simple Calculator
6. Matrix Operation Using Scilab
7. Matrices – Addition & Subtraction
8 Matrices – Multiplication
9. Identity Matrix & Inverse of Matrix
10. Solve Linear Equations by Matrices
11. Transpose of Matrix
12. Determinant of Matrix
13. Eigenvalues and Eigenvectors
14. SciNotes - Storage of Programs in Scilab
15. Display Data Using mprintf()
16. If Else Conditional Statements
17. For Loops
18. While Loops
19 Select Case Conditional Statements
20. Custom Functions
21. Importing Data
22. 2D Plotting
23. Application Development
24. XCOS Simulations

VII. Bibliography
VIII Index
IX. Other Books by Author
X. About the Author
V List of Figures
Fig. 4.1 Scilab environment

Fig. 4.2 Scilab preferences

Fig. 4.3 Variable Browser showing the entered values

Fig. 4.4 Command history

Fig. 14.1 SciNotes Ikon to start the Scilab’s embedded text editor

Fig. 14.2 SciNotes text editor

Fig. 15.1 'mprintf' output to screen

Fig. 16.1 Flow chart for a simple for-loop

Fig. 16.2 Flow chart for a nested for-loop

Fig. 17.1 Flow chart for a typical while-loop

Fig. 20.1 Function Object in Scilab

Fig. 20.2 Function 'SinePlot'

Fig. 20.3 Variable Browser

Fig. 21.1 Plot of data imported using 'csvRead'

Fig. 22.1 Polyline Properties

Fig. 22.2 Plotting using 'plot2d'

Fig. 22.3 Plotting from an array

Fig. 22.4 Better presentation with 'plot2d'


Fig. 22.5 'plot' command in Scilab

Fig. 22.6 Subplot example

Fig. 22.7 Subplot - 6 images in one window

Fig. 22.8 Using LaTeX in Scilab

Fig. 23.1 FileName flowchart

Fig. 23.2 Option flowchart

Fig. 23.3 Plot with the normal 'xgrid' command

Fig. 23.4 Plot with the 'x_ticks' command

Fig. 23.5 Polyline property and thickness changed

Fig. 23.6 Single-row plotting

Fig. 23.7 Multiple-column plotting

Fig. 24.1 Role of simulation

Fig. 24.2 Control System in time-domain

Fig. 24.3 Control system seen from time and frequency domains

Fig. 24.4 System transfer function in the s-domain

Fig. 24.5 Step response of a first-order system

Fig. 24.6 Parameter-setting for XCOS simulation

Fig. 24.7 Ramp input simulation in XCOS for a first-order system


1 Scilab Basics - Introduction
Silab and XCOS (“Scilab 6.1.0 | Www.Scilab.Org.”) are well-known design
and analysis tools for control systems. These will be used extensively in this
series on control systems. This text includes all the basic functions of this two
software for familiarisation and practice. The knowledge gained would be a
prerequisite for the other volumes of series on control systems, where Scilab
and XCOS are frequently applied.

Scilab is an open-source alternative to the industry-standard


program MATLAB. Scilab, which also incorporates XCOS, is a free open
source software for numerical computation and simulation, similar to
MatLab® and Simulink®. Scilab is created by INRIA (the French national
institute for research in computer science and control). http://www.scilab.org/

It is a suitable program for application in control system design and analysis.


In this text, Scilab 6.1.0 is implemented on Linux OS - Peppermint
10/Ubuntu 19.10/Linux Mint 19.3.
Who This Book Is Intended For
The book is mainly written for budding marine engineers, who would like to
have a better grasp of an Industry-standard software to apply to their problem
domain, especially in the area of control systems.

The book is also aimed at the engineers, without any programming


background, who will not be intimidated to have some hands-on experience
in the Scilab environment.

Finally, the book is also for anyone interested to get a head-start in Scilab,
which has so many applications in science and engineering.

This book is primarily a hands-on companion for Scilab users at the


beginners’ level. Those looking for a deeper theoretical under-peening on
Scilab are advised to look up the following well-written references on Scilab:

1) Introduction to Scilab: For Engineers and Scientists Paperback by


Sandeep Nagar, 2017

2) Introduction to Scilab by Rachna Verma and Arvind Verma, 2018


3 Scilab Installation
To install Scilab,
By the end of this Section, you will be able download the program
to… from
1. Install Scilab in a Linux environment
computer.
2. Install Scilab in an MS Windows
environment computer.
3. Install Scilab in an Apple Mac
environment.

https://www.scilab.org/download and extract the program. The extracted


folder could be renamed as just ‘scilab’ for ease of use and moved to the
‘Home’ directory (in a Linux environment). Sample bash lines in a file
named scilab.sh could be used for starting the program from the desktop.

Once the file is written, one needs to provide permission to use the file using
the following code in the terminal.

sudo chmod +x scilab.sh

A sample bash program is shown below.

Bash Program

#!/bin/bash

echo "...Starting Scilab...wait!!"

cd

cd /home/kalyansg

cd scilab
cd bin

./scilab

For a MS Windows 10 installation, download the exe file and run the exe file
and follow the prompts. It will end up with a starting icon. The program can
be easily started by double-clicking the starting icon.
For Apple Mac users, follow these steps below:

1. Press Command+Space and type Terminal and press enter/return key.


2. Run in Terminal app: ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)" <
/dev/null 2> /dev/null ; brew install caskroom/cask/brew-cask 2>
/dev/null and press enter/return key.
3. If the screen prompts you to enter a password, please enter your Mac's
user password to continue. When you type the password, it won't be
displayed on the screen, but the system would accept it. So just type
your password and press ENTER/RETURN key. Then wait for the
command to finish.
4. Run: brew cask install scilab

Done! Scilab can now be used.


4 Scilab Environment
When you start Scilab
By the end of this Section, you will be able you get the following
to… start-page with the
docked windows as
1. State the functions of 'Scilab Console'.
shown below with
2. State the functions of 'File Browser'. console in the middle,
3. State the functions of 'Variable Browser'. files browser at the left,
variables browser,
4. State the functions of 'Command History'. command history, and
news feed on the right.

Figure 4.1 Scilab environment

[Note: If, by chance, a window is undocked - To Re-dock windows (file


browser, variable browser, command history). Do the following:
Edit--> Preferences-->General-->Desktop Layout : Select a layout -->
in the drop-down combo box, select integrated. Important Note: if
already integrated is selected Change it to simple and again select
integrated and click ok. Close Scilab and Restart.]

Console: It is the Scilab’s main workspace. After the command prompt “ --


>“, just enter a command and press enter. The answer will follow. For
example: Define two variables, A = 5 and B=10. See the console entries &
their responses below. [all entries on the right of // are ignored by the Scilab
interpreter – meant only for comments and NOT execution.]

--> clear // clear all values of variables


--> A=5 // Declare variable A as 5
A =
5.
--> B=10 // Declare variable B as 10
B =
10.
--> C=A*B // Declare variable C as multiplication of A & B
C =
50.
--> disp(A,B,C) // disp – Display – Notice C is displayed first
50.
10.
5.

File Browser: Set up your default data site for storing Scilab files. Go to
Scilab Preferences, choose under General>Start-up directory>Use default
directory (shown in the picture below).
Figure 4.2 Scilab preferences

Variable Browser: It lists the variables used and details their names, values,
type, and visibility. Any change in the values is also updated.

--> A=10
A=
10.
--> b="Trial"
b=
Trial
--> B=25
B=
25.
--> C=A+B
C=
35.
--> K=[2 3 4;6 7 8;9 1 4]
K=
2. 3. 4.
6. 7. 8.
9. 1. 4.

Figure 4.3 Variable Browser showing the entered values

Command History: It contains the commands typed so far. All commands


entered in a given Scilab session get stored in this docked window, making
them accessible for reuse or editing. The command history has a date and
time stamp.

Figure 4.4 Command History

News Feed: It displays news about Scilab products and activities to keep the
users updated.
5 Scilab as a Simple Calculator
Scilab can work as a
By the end of this Section, you will be able simple calculator and it
to… can also be used to
define variables and
1. Undertake arithmetic operation in the
store values in them for
'Scilab Console'.
subsequent
2. Evaluate trigonometric functions in Scilab calculations. This is
interactive mode. shown in the following
3. Assign variables with specified values. Scilab examples.
(Ariba, “Introduction
4. Carry out logical operations in Scilab to Scilab.”)
interactive mode.

--> 4+4
ans =
8.
--> 25*4
ans =
100.
--> a=12;b=3;
--> c=a*b;
--> disp(c) // ’disp’ is command for ‘display’ the variable value
36.
--> d=%pi/3;//Here %pi is 3.14159265 (π)
--> disp(d)
1.0471976
--> a=12;
--> b=sqrt(a) // ’sqrt’ is the command for ‘square root’
3.4641016
--> b=a^2; // 'b' is redefined
--> disp(b)
144.
--> disp (sqrt(b))
12.

[Note: ‘//’ indicates comments and anything written after // is ignored]

Elementary Operators

The following are the elementary operators in Scilab:

+ addition
- subtraction
* multiplication
/ right division
\ left division
^ exponent

Scilab Implementation:

--> a=10
a =
10.
--> b=2
b =
2.
--> a+b
ans =
12.
--> a-b
ans =
8.
--> a/b
ans =
5.
--> a\b
ans =
0.2
--> a^b
ans =
100.
--> b/a
ans =
0.2

Note: All follow normal rules of arithmetic except the left division, where a\b
= b/a

Common Built-in Functions

FUNCTION SCILAB SYMBOL Some examples on


Scilab:
square root sqrt(x) √x
--> x=%pi/4 // %pi
exponential exp(x)
is π, which is 180
degrees. 180/4 is 45
natural algorithm log(x) ln(x)
degrees
decimal logarithm log10(x) log(x) x =
0.7853982
absolute value abs(x) |x| --> sin(x)
ans =
sine sin(x) sin(x), x in radians
0.7071068
cosine cos(x) cos(x), x in radians --> y=%pi/6 // %pi is
π, which is 180
tangent tan(x) tan(x), x in radians degrees. 180/6 is 30
degrees
cotangent cotg(x) cot(x), x in radians
y =
arc-sine asin(x) y=arcsin(x),x=sin(y) 0.5235988
--> sin(y)
arc-cosine acos(x) y=arccos(x),x=cos(y) ans =
0.5000000
arc-tangent atan(x) y=arctan(x),x=tan(y)

minimum min(x) min x=[x1,x2,…] --> A =[20, 39, 45, 7,


56, 99, 1, 0] // defines
maximum max(x) max x=[x1,x2,…] an array of numbers
A =
20. 39. 45. 7. 56. 99. 1. 0.
--> max(A)
ans =
99.
--> min(A)
ans =
0.
-->X=[1,2,5]; Y=[5,3,5];. -->X==Y ans = F F T

Logical Operators

LOGICAL SCILAB EXAMPLE Important Built-in


OPERATOR Constants
Logical and & --> %F & %T
ans =
F Assigning Variable
Logical or | --> %F | %T In Scilab, a variable is
ans =
T assigned by the
operator '='. This is not
Logical not ~ -->~ %F to be confused with the
ans =
T
mathematical 'equal'.

equal == -->x=[1,2,5];y=[5,2,5]; For example:


x==y
ans =
FTT --> A=10
A =
not equal to <> ~= x=5; y=10; 10.
x<>y
ans =
Can be again redefined
T anytime in the
program:
less than < x=5; y=10; --> A=15
x<y
ans = A =
T 15.
less than equal <= i=1
to while i<=2
Scilab is case-sensitive
a(i)=input('Enter an - 'A' and 'a' can be
integer: ', "string")
b(i)=strtod(a(i)) declared as separate
disp(b(i)) variables.
i=i+1
end
Console Output:
Enter an integer: 3
3
Enter an integer: 4
4
-->i
i=
3

more than > x=5; y=10;


y>x
ans =
T

more than >= Similar to <=


equal to

boolean value %T Shown above under 'less


true than'

boolean value %F Shown above under


false 'equal'

Scilab
Built-in Description
Constants

%i Imaginary unit (√−1)

Ratio of circumference to diameter of a


%pi
circle; (π= 3.14159···)

%e Euler’s constant (e= 2.7182818···)

%inf Infinity (∞)

%nan Not a number

%s Polynomials=poly(0,'s')
%z Polynomials=poly(0,'z')
6 Matrix Operation Using Scilab
Matrices are
By the end of this Section, you will be able rectangular grids,
to… frequently used in
science and
1. Enter a matrix in Scilab.
engineering for
2. Edit a matrix in Scilab. representing
3. Create arrays in Scilab. mathematical
equations. Matrices are
4. Describe characteristics of also used for storing
matrices/arrays/vectors in Scilab. and manipulation of
various types of data.
Complicated calculations can be solved through the manipulation of matrices.
(Hardesty 2013)

Matrices, a great tool from linear algebra, are increasingly used to analyse
control systems. This text will cover all the basics of matrix operations using
Scilab, which simplifies these calculations.

Figure 6.1 A typical matrix

A matrix can be entered in Scilab 6.1.0 in several ways as shown below in the
three examples:
--> A = [10 4 20 5 // Type the first line then press Enter
> 3 4 7 10 // Type the second line then press Enter matrix
> 5 1 6 1] // Type the last line with a closing bracket at the end
A =

10. 4. 20. 5.
3. 4. 7. 10.
5. 1. 6. 1.

--> B=[3,4,5;7,8,9;3,2,1] // Type the entire matrix in one line using


comma & semi colon
B =

3. 4. 5.
7. 8. 9.
3. 2. 1.

--> C = [7 2 4;3 2 10] // Type the entire matrix in one line using gap &
semi colon
C =

7. 2. 4.
3. 2. 10.

Once a variable is defined, it can be edited as shown below with the variable
A: (SHASHIKANT, “Editing Vectors and Matrices in Scilab – x-
Engineer.Org.”)

--> A = [10 4 20 5 // Type the first line then press Enter


> 3 4 7 10 // Type the second line then press Enter matrix
> 5 1 6 1] // Type the last line with a closing bracket at the end
A =

10. 4. 20. 5.
3. 4. 7. 10.
5. 1. 6. 1.

--> A (3,4)= 75 // Changing the value of the element A34


A =

10. 4. 20. 5.
3. 4. 7. 10.
5. 1. 6. 75.

--> editvar A // Another way of changing the value of the variable -


more elements can be changed at once by this method with a table-
input.

Figure 6.2 Editing element values using editvar command A34 changed from
75 to 60

--> A
A =

10. 4. 20. 5.
3. 4. 7. 10.
5. 1. 6. 60.

6.1 Notes on Matrices/Vectors/Arrays in Scilab


• A matrix is a set of real or complex numbers (referred to as elements)
arranged in rows and columns to form a rectangular array.
• The matrix above with '4' rows and '3' columns is referred to as '4 x 3'
matrix having order 4 x 3.
• Matrices can only be added when they are of the same order.
• When a matrix has the same number of rows and columns, it is called a
square matrix. For example, 'A', a 4-by-4 matrix, is known as a square
matrix of order 4. Two square matrices, having the same order, can be
added and multiplied.
• Rows and columns of a matrix cannot be interchanged and it has no
numerical value.
• A matrix with one row or one column is named a vector. Vectors and
matrices are not differentiated in Scilab.
• If the first row, as an example, has 4 elements, the second row must
also have 4 elements. Otherwise, Scilab will output an error message.
• All variables in a matrix in Scilab are of the type “Double”.
• An array consists of a set of elements, which are called values or
variables, identified by a minimum of one array index or key.
• An array is stored such that the position of every element is often
computed from its index tuple by a mathematical formula. The simplest
sort of arrangement may be a linear array, also called a one-
dimensional array. Arrays could also be multi-dimensional. “Array
Data Structure, Wikipedia.”
6.2 Creating an Array in Scilab

--> t=0:0.2:2// Creating an array between 0 and 2 with difference of 0.2


between adjacent cells
t =

0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2.


7 Matrices – Addition & Subtraction
Two matrices may be
By the end of this Section, you will be able added or subtracted
to… only if they have the
same dimension; that
1. Add two matrices in Scilab.
is, they must have the
2. Subtract a matrix from another in Scilab. same number of rows
3. Describe when addition and subtraction of and columns. Addition
matrices could be carried out. or subtraction is
accomplished by
adding or subtracting
corresponding elements.
The following example shows an example of addition & subtraction in
Scilab.

--> A = [1 4 7 8
>3289
> 2 5 1 1]
A =
1. 4. 7. 8.
3. 2. 8. 9.
2. 5. 1. 1.

--> B = [7 3 2 1
>5632
> 1 2 9 2]
B =
7. 3. 2. 1.
5. 6. 3. 2.
1. 2. 9. 2.

--> C=A+B
C =
8. 7. 9. 9.
8. 8. 11. 11.
3. 7. 10. 3.

--> D=A-B
D =
-6. 1. 5. 7.
-2. -4. 5. 7.
1. 3. -8. -1.
8 Matrices – Multiplication
Assuming the
By the end of this Section, you will be able following two matrices
to… are to be multiplied.
1. Multiply two matrices in Scilab.
2. State the rules of matrix-multiplication.

The results will be in the following form:

where,
a = (first row * first column)
= (3*6 + 4*1 + 7*6) = 64
b = (first row * second column)
= (3*2 + 4*5 + 7*4) = 54
c = (second row * first column)
= (2*6 + 3*1 + 1*6) = 21
d = (second row * second column)
= (2*2 + 3*5 + 1*4) = 23

This could be done in Scilab environment with the click of a button:

--> A = [3 4 7
> 2 3 1] // entering the first matrix into Scilab
A =
3. 4. 7.
2. 3. 1.

--> B =[6 2
>15
> 6 4] // entering the second matrix into Scilab
B =
6. 2.
1. 5.
6. 4.
--> C=A*B // multiplying the two matrices in Scilab - it matches the
manual results shown above.
C =
64. 54.
21. 23.

Extending the above problem with the following two matrices - the second
matrix is modified by adding row [8 1].

Now, the multiplication of these two matrices will be attempted in Scilab.

--> A = [3 4 7
> 2 3 1] // entering the first matrix into Scilab
A =
3. 4. 7.
2. 3. 1.
--> B = [6 2
>15
>64
> 8 1] // entering the second matrix into Scilab
B =

6. 2.
1. 5.
6. 4.
8. 1.
--> C = A*B // trying to multiply the two matrices in Scilab
Inconsistent row/column dimensions.

Rule of matrix multiplication:


For multiplying two matrices, the number of columns in the first matrix must
be equal to the number of rows in the second matrix. (Stroud and Booth,
Engineering Mathematics. p.540)

In the above example, matrix A has a dimension 2 x 3 or 2 rows by 3


columns. So, for valid multiplication, the second matrix B should have 3
rows (no less or no more). However, if we make a mistake, Scilab will
provide the error message “inconsistent row/column dimensions”.
9 Identity Matrix & Inverse of Matrix
The identity matrix is a
By the end of this Section, you will be able square matrix that has
to… 1’s along the main
diagonal and 0’s for all
1. Define identity matrices in Scilab.
other entries. They are
2. Inverse a matrix in Scilab. usually denoted by I.
3. Allocate inverse of a particular matrix to a There are two
variable. examples below I3 &
4. State that when a matrix is multiplied by I2.
an identity matrix of the same order, it
results in the matrix itself.

Multiplying any matrix by the identity results in the matrix itself. As an


example, if a matrix

The inverse of matrix A is found using Scilab as shown below.

--> A=[3 4;2 1] // Defining a matrix A in Scilab


A =
3. 4.
2. 1.
--> B = inv(A) // Allocating inverse of A to a variable B
B =
-0.2 0.8
0.4 -0.6
--> C=A*B // Allocating (A x B) to a variable C
C =
1. 0.
0. 1.

Note: B is A-1. So, when multiplication of (A x B) or (A x A-1) is


performed, the result is an identity matrix I. So, it is concluded,
A*A-1 = I (Identity Matrix)
Also, it can be shown using the above process,

So, it is shown clearly that any matrix when multiplied by an identity


matrix of the same order results in the matrix itself.

One can generate an identity matrix using the ‘eye’ command in Scilab.
--> I=eye(4,4)
I =
1. 0. 0. 0.
0. 1. 0. 0.
0. 0. 1. 0.
0. 0. 0. 1.
--> I = eye(3,3)
I =
1. 0. 0.
0. 1. 0.
0. 0. 1.
10 Solve Linear Equations by Matrices
With the basic
By the end of this Section, you will be able knowledge of Scilab,
to… detailed in the previous
sections, it will be
1. Represent linear equations in a matrix
possible to solve linear
format.
equations. Assuming
2. State X = A-1 .B as the solution in the the following three
matrix format for a set of linear equations. equations are given,
3. Solve linear equations in Scilab.

7x+5y-3z = 16 (1)
3x-5y+2z = -8 (2)
5x+3y-7z = 0 (3)

• The first step is to convert them into a matrix format


• There will be three matrices:
◦ Matrix A representing the coefficients of the variables
◦ Matrix X representing the variable x, y, and z (the unknowns – which
we need to find out) and
◦ Matrix B representing the constants, not associated with the variables
directly.

7x+5y-3z = 16 (1)
3x-5y+2z = -8 (2)
5x+3y-7z = 0 (3)
Rewriting in the format of the 3 equations,

Or, A.X = B
To eliminate A, multiplying both sides by A-1
Or, A-1.A.X = A-1 .B [But A-1.A = I]
Or, I.X = A-1 .B [But I.X = X]
Or, X = A-1 .B [This is the final solution]

Using Scilab the solution will be as follows:

--> A = [7 5 -3;3 -5 2;5 3 -7]


A =
7. 5. -3.
3. -5. 2.
5. 3. -7.
--> B=[16;-8;0]
B =
16.
-8.
0.
--> C=inv(A)
C =
0.1132812 0.1015625 -0.0195313
0.1210938 -0.1328125 -0.0898438
0.1328125 0.015625 -0.1953125
--> X=C*B
X =
1.
3.
2.
Hence, x=1, y=3 and z = 2

There are four unknowns in the following set of linear equations. Four
unknowns are to be solved using Scilab.

3w + 5x - 3y - 2z = 34
- 2w + 2x + 6y + 3z = 2
w + 4x + 2y - z = 31
6w + x + y + z = 7
(w, x, y, z) = (_, _, _, _)

The answers are w = 1, x = 5, y = 2, z = -6

The first step is to convert the equations in to a matrix format:

--> A=[3 5 -3 -2
> -2 2 6 3
> 1 4 2 -1
> 6 1 1 1]
A =
3. 5. -3. -2.
-2. 2. 6. 3.
1. 4. 2. -1.
6. 1. 1. 1.

--> B=[34;2;31;7]
B =
34.
2.
31.
7.
--> C=inv(A)
C =
-0.0461538 -0.0666667 0.0512821 0.1589744
0.2076923 0.1333333 -0.0641026 -0.0487179
-0.2384615 -0.0666667 0.3205128 0.0435897
0.3076923 0.3333333 -0.5641026 0.0512821

--> X=C*B
X =
1.
5.
2.
-6.

These values match the given answers.


11 Transpose of Matrix
Transpose of a matrix
By the end of this Section, you will be able is when its rows
to… become columns and
its columns become
1. Get the transpose of a matrix in Scilab.
rows.

Assume a matrix A =
2 4 6 8
3 7 9 3
8 9 7 1

Transpose of A = A’ =
2 3 8
4 7 9
6 9 7
8 3 1

Trying this with Scilab

--> A = [ 2 4 6 8
>3793
> 8 9 7 1]
A =
2. 4. 6. 8.
3. 7. 9. 3.
8. 9. 7. 1.
--> B=A'
B =
2. 3. 8.
4. 7. 9.
6. 9. 7.
8. 3. 1.
12 Determinant of Matrix
Determinants of
By the end of this Section, you will be able matrices are useful in
to… solving a system of
linear equations. It
1. Evaluate the determinant of a matrix
applies to only square
using Scilab.
matrices. For a square
2. State the type of matrix for which matrix A it’s
determinant could be found. determinant is denoted
3. Calculate the determinant of a 2x2 matrix by ∣A∣
manually.

For a numerical example assume,

In Scilab,

--> A=[5 4
> 3 6]
A =
5. 4.
3. 6.
--> B=det(A)
B =
18.

For a 3 x 3 Matrix, the determinant is given by:

The top part of the above figure shows which elements to be avoided by
struck-out lines.

A numerical example:

= 1(6 – 8) – 4(21 – 5) + 3(56 – 10)


= – 2 – 64 + 138
= 72

In Scilab:

--> A=[1 4 3
>721
> 5 8 3]
A =
1. 4. 3.
7. 2. 1.
5. 8. 3.

--> B=det(A)
B =
72.
13 Eigenvalues and Eigenvectors
This topic will be
By the end of this Section, you will be able useful in the state-
to… space form of analysis
(a state-space
1. State that if a system has a strictly real
representation is a
eigenvalue, the system will either
mathematical model of
exponentially decrease or increase in the
a physical system as a
corresponding eigenvector direction.
set of input, output, and
2. State that if a system has a pair of state variables related
complex conjugate eigenvalues, the system by first-order
will oscillate around the directions given by differential equations.
the corresponding eigenvectors while either “Wikipedia - State-
exponentially decreasing towards the origin, Space
or increasing away from it according to the Representation”),
signal of the eigenvalues real part. especially, while
3. State that det(A−λI) = |A−λI| = 0 is called dealing with the
the characteristic equation of the matrix A stability of a system.
Eigenvalues are
4. Evaluate eigenvalues and eigenvectors related to poles of the
using Scilab. system, which deal
with stability. Each
pole of a system (In Transfer Function form), is an eigenvalue of the relevant
matrix (In State-Space form). Eigenvalues with negative real parts indicate
that poles of the system are in the left half-plane and are stable. The topic
will be covered in greater detail under the state-space and stability topics. The
underlying discussion can be revisited prior to covering these topics. Link
here refers to a good discussion on the topic. (“What Is the Intuition of
Eigenvector and Eigenvalue from a Control System Perspective?” - Forum
Post)

Considering a system of n equations in n unknowns,


In the matrix form,

Which can be written as


A.X = M
where,
A is a n x n matrix, called the coefficient matrix
X is a n x 1 column vector of unknowns, and
M is a n x 1 column vector of constants.

If it occurs that M is a scalar multiple of X,


then
A.X = λ.X [where λ is a scalar]

Then X is an eigenvector of the linear transformation A and the scale factor λ


is the eigenvalue corresponding to that eigenvector
Rearranging,
(A - λ).X = 0
If X ≠ 0
A-λ=0

Writing both terms above in matrix form,

A - Iλ = 0 [where I is an identity matrix of the same order as matrix A]

det(A−λI) = |A−λI| = 0 is called the characteristic equation of the matrix


A

13.1 Example

To find the eigenvalues for the following 3 x 3 matrix,

Using the equation A - Iλ = 0,

Or,
Or,

Or,

So, λ = 1 is the first solution (eigenvalue)


And,

Or,

Using the standard solution for a quadratic equation,


Or,

Or,

Or,

Hence, there are three eigenvalues for the given 3 x 3 matrix 1, 4 & - 0.5

Using Scilab the solution is easier as shown below:

--> A=[1 0 0
> 0 2 2.5
> 0 2 1.5]
A =

1. 0. 0.
0. 2. 2.5
0. 2. 1.5
--> spec(A)// outputs the eigenvalues
ans =

-0.5 + 0.i
4. + 0.i
1. + 0.i

To find the corresponding eigenvector for, say, when the eigenvalue is 4, the
expressions are written in the matrix form.

Or,

Or,

Or,

So, the eigenvector is any non-zero multiple of this:


Using Scilab, the following are obtained:

For the eigenvalue 4, the eigenvector is given in column 2 of ‘c’.


The eigenvectors are found to be in the same ratio as the manual solution.
14 SciNotes - Storage of Programs in Scilab
Inputs to Scilab could
By the end of this Section, you will be able be in two ways:
to…
Through Console -
1. Describe the functions of embedded Used when the entered
SciNotes text editor in Scilab. codes are short and the
2. Write simple input-output code in Scilab interpretation is
SciNotes, store, and execute the same. required immediately.
3. Use 'disp' command for 'string' and All examples in the
'double' variable types on the same line. earlier sections were
entered using this
4. State that anything typed after '//' would mode of entry.
be ignored by the Scilab interpreter and is Through Scilab's own
used for providing comments to a program embedded text editor
line. SciNotes - Used when
the entered codes are
long and codes are saved as a stored program. This could be run later
after storage and could be edited by retrieving the program at any time.

This section deals with the working of the SciNotes, which can be started
clicking the SciNotes ikon shown below.

Figure 14.1 SciNotes Ikon to start the Scilab’s embedded text editor

On opening the text editor opens up:


Figure 14.2 SciNotes text editor

As an example, the following simple input-output codes are entered in the


text editor:

0001 x = input('What is your name? : ', "string") // Seeking a user-input


in string - command input
0002 disp('So, your name is ', x) // Displaying the user-input as a
confirmation - command disp

0001 & 0002 refer to line numbers in the program.


The codes could be saved at a preferred location using *.sce or *.sci
extensions. It is recommended to use *.sce because *.sci is more related to
user-defined functions.

After saving the execution button ⊳ in SciNotes would execute the saved
program. Alternatively, the save-execute button (shown above in figure
14.2) can be used, which saves the file first and subsequently executes the
program in the Console.

The execution in the Console is shown below:

Startup execution:
loading initial environment

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-001.sce', -1)


What is your name? : Kalyan

"So, your name is "

"Kalyan"

However, the output is not formatted and the name comes in the second line,
which is not ideal.

The code could be improved with the following modification using a '+'
operator:

0001 x = input('What is your name? : ', "string")//Seeking a user-input


in string
0002 disp('So, your name is '+ string (x))// Concatenation of two strings
is made by a +

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-002.sce', -1)


What is your name? : Kalyan

"So, your name is Kalyan"


Another longer example is shown below:

0001 name = input("Enter your name: ", "string")


0002 age = input("Enter your age: ", "string")
0003 city = input("Enter your city: ", "string")
0004
0005 disp('Your name is '+ string (name)+', your age is '+ string(age)
+' and you are from '+ string(city))

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-003.sce', -1)


Enter your name: Sam
Enter your age: 26
Enter your city: Singapore

"Your name is Sam, your age is 26 and you are from Singapore"

It is possible to do some simple math-operation using 'disp' command:

0001 A = input("Enter a number: ", "string")


0002 B = input("Enter another number: ", "string")
0003
0004 disp(string(A)+' plus '+string(B)+' equals '+string(A+B));

Console output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-004.sce', -1)


Enter a number: 20
Enter another number: 30

"20 plus 30 equals 2030"

However, instead of adding, the numbers were treated as strings in Scilab.


Checking the type of variable in the Console,

--> type(A) // Command 'type' is used to check the variable type


ans =
10.

--> type(B)
ans =
10.

'10' refers to variable type 'string'. The code is modified with default variable
type without specifying string:

0001 A = input("Enter a number: ")


0002 B = input("Enter another number: ")
0003
0004 disp(string(A)+' plus '+string(B)+' = '+string(A+B));

Console output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-005.sce', -1)

Enter a number: 20
Enter another number: 30

"20 plus 30 = 50"

Checking the type of variable in the Console,

--> type(A)
ans =
1.

--> type(B)
ans =
1.
'1' refers to variable type 'real'.

'typeof' can also be used to check the variable type,


"20 plus 30 equals 2030"

--> typeof(A)
ans =
"string"

"20 plus 30 = 50"

--> typeof(A)
ans =

"constant"

Scilab Variable List

type(x) returns an integer which is the type of x as given in the list


below.

1 - a real or complex matrix of double.


2 - a polynomial matrix.
4 - a boolean matrix.
5 - a sparse matrix.
6 - a sparse boolean matrix.
7 - Matlab sparse matrix
8 - a matrix of integers stored on 1 (int8), 2 (int16) or 4 (int32) bytes.
9 - a matrix of graphic handles.
10 - a matrix of character strings.
11 - an un-compiled function (Scilab code). A function created with
deff with argument 'n'.
13 - a compiled function (Scilab code).
14 - a function library.
15 - a list.
16 - a typed list (tlist).
17 - a matrix oriented typed list (mlist).
128 - a pointer (Use case: lufact).
129 - a size implicit polynomial used for indexing.
130 - a built-in Scilab function, called also gateway (C, C++ or Fortran
code).
15 Display Data Using mprintf()
While programming
By the end of this Section, you will be able there is a need to
to… display the values of
variables in the Scilab
1. Display strings and variables using
console to output the
'mprintf' command.
final results of the
2. Use '\n' to display information in a new script/algorithm. The
line. best way to display the
3. Create a table using 'mprintf' command. values of the variables
is by using the
“mprintf()” function.
(x-engineer.org)

Considering the following example entered in SciNotes:

0001 a=input("Enter an integer between 1 & 10 : ");


0002 b=input("Enter another integer between 1 & 10 : ");
0003
0004 h = sqrt (x^2 + y^2);// h could be a float
0005
0006 mprintf('Hypotenuse for the right angle triangle with sides
%i,and %i \n is given by:h = %f',a,b,h)

Here %i stands for integer (first for 'a' and then for 'b') and %f stands for float
(h). \n transfers the output to a new line.

Running the program the Console output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-006.sce', -1)


Enter an integer between 1 & 10 : 7

Enter another integer between 1 & 10 : 3

Hypotenuse for the right angle triangle with sides 7,and 3


is given by:h = 7.615773

The general structure of the format for mprintf is:

format --> [escape]%,[flag],[width][.precision]specifier (see explanation


below).

There are two under-mentioned mandatory fields needed for the function
'mprintf' to work. The other fields, in square brackets [ ] above, are optional.

1. percent sign (%): this informs the function that a formatting sequence
begins
2. specifier: this describes what type of data will be displayed

'format' detailed functions:

escape - There are two escape sequences used by mprintf in Scilab:


\n – Signals the start of a new line for display
\t – Horizontal tab, moves the start of the display towards the right with
a predefined number of spaces

Flags - Used to format the alignment of the displayed data or to add a


prefix for octal and hexadecimal data types:
- (minus sign) – Aligns the displayed data to the left side; the flag has
effect on used with [width] field
+ (plus sign) – Forces the display of the sign for both negative and
positive numbers
# (hash) – If used with specifiers (%o, %x and %X) will add a prefix
before the data: 0x for %x, 0X for %X and 0 for %o
0 (zero) – When the [width] field is specified will replace left empty
spaces with 0 (zeros)

width - It is a positive integer number that defines how many character


places are used for data display. By using 0 before the width number the
empty spaces could be filled with zeros
.precision - It is also a positive integer number that defines how many
places are used for the decimal part of the displayed data

specifier - Keyword used to define the data type of the data to be


displayed. Scilab supports the following data types:
%c – displays a unique character
%s – displays a string of characters
%d – displays an integer decimal number with sign
%i – displays an integer decimal number with sign
%u – displays an integer decimal number without sign
%f – displays a real number with sign
%g – displays a real number with sign in a short format (fewer decimal
places)
%e – displays a real number with sign in exponential format
%x – displays a hexadecimal number (only unsigned integers)Instead of
%e or %x we can use %E and %X, the only difference is that the string
characters are going to be upper case letters.

Example showing \n \t escape sequences:

SciNotes Code:

0001 a=input("Enter an integer between 1 & 10 : ");


0002 b=input("Enter another integer between 1 & 10 : ");
0003
0004 h = sqrt (a^2 + b^2);
0005
0006 mprintf('\n\tLine zero (indented) CALCULATION FOR A
RIGHT-ANGLE TRIANGLE\nLine one Side one is %i
\nLine two Side two is %i \nLine three Hypotenuse for the right-angle
triangle h = %f',a,b,h)

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-007.sce', -1)


Enter an integer between 1 & 10 : 3
Enter another integer between 1 & 10 : 7

Line zero (indented) CALCULATION FOR A RIGHT-ANGLE


TRIANGLE
Line one Side one is 3
Line two Side two is 7
Line three Hypotenuse for the right-angle triangle h = 7.615773

'mprintf' can also be used to display a table on the Console. (x-engineer.org)


'disp' text output is not so elegant.

Example showing a 'disp' usage:

SciNotes Code:

0001 i=1
0002 a= input("Enter length of side-one in cm: ")
0003 b= input("Enter length of side-two in cm: ")
0004
0005 disp('SIDE-1, SIDE-2 & HYPOTENUSE OF A RIGHT-ANGLE
TRIAGE')
0006
0007 for i=1:5 // for-end loop: index i between 1 & 5 incrementing by
+1 in every loop
0008 c(i)=a
0009 d(i)=b
0010
0011 h1=sqrt(a^2 + b^2)
0012 h(i)=h1
0013
0014 disp('Side_1='+string (a)+'cm '+ 'Side_2='+string (b)+'cm
'+'Hypotenuse= '+string (h(i))+'cm')
0015
0016 a=a+1//incrementing by +1
0017 b=b+1//incrementing by +1
0018 end
Console Output:

exec('/home/kalyansg/Dropbox/scilab-data/User-Input-008.sce', -1)
Enter length of side-one in cm: 3

Enter length of side-two in cm: 5

"SIDE-1, SIDE-2 & HYPOTENUSE OF A RIGHT-ANGLE TRIAGE"

"Side_1=3cm Side_2=5cm Hypotenuse= 5.8309519cm"

"Side_1=4cm Side_2=6cm Hypotenuse= 7.2111026cm"

"Side_1=5cm Side_2=7cm Hypotenuse= 8.6023253cm"

"Side_1=6cm Side_2=8cm Hypotenuse= 10cm"

"Side_1=7cm Side_2=9cm Hypotenuse= 11.401754cm"

Better formatting can be obtained using 'mprintf':

SciNotes Code:

0001 i=1
0002 a= input("Enter length of side-one in cm: ")
0003 b= input("Enter length of side-two in cm: ")
0004
0005 mprintf('\nSide-1\tSide-2\tHypoteneuse\n')
0006 mprintf('[cm]\t[cm]\t[cm]\n')
0007
0008 for i=1:5 // for-end loop: index i between 1 & 5 incrementing by
+1 in every loop
0009 c(i)=a
0010 d(i)=b
0011
0012 h1=sqrt(a^2 + b^2)
0013 h(i)=h10014
0015 mprintf('%d \t %d\t%.2f\n',c(i),d(i),h(i))
0016
0017 a=a+1//incrementing by +1
0018 b=b+1//incrementing by +1
0019 end

Console Output in a table-format:

Figure 15.1 'mprintf' output to the screen


16 If Else Conditional Statements
Tasks would be
By the end of this Section, you will be able undertaken if a
to… condition or a set of
conditions is true. ("IF
1. Write executable codes using If-then-else-
ELSE Conditional
end command.
Statements – x-
2. Write executable codes using If-then- Engineer.Org)”
elseif-else-end command.
3. Use 'isnan' command. The general structure
of if-else conditional
statements are shown
below:

If Condition True then


Task-1
Task-2
---------

Else
Task(s) for if-condition False
End

Example codes of if-else conditional statements are shown below:

SciNotes Code:

0001 clear all


0002 clc
0003
0004 A=input("Enter a number: ")
0005
0006 B=input("Enter a string e.g E,F, etc: ","string")
0007
0008 disp('A is '+typeof(A))//check the type of variable for A
0009 disp('B is '+typeof(B))//check the type of variable for B
0010
0011 if (isnan(A)) then disp("A is a STRING")//isnan - checking whether
A is 'not a number' statement is true 0012 else disp("A is of course a
CONSTANT")
0013 end
0014
0015 B=strtod(B)//Converting string to number - but as B is a string B
becomes a 'nan' or 'Not A Number'
0016
0017 if (isnan(B)) then disp("B is of course a STRING")//isnan -
checking whether B is 'not a number' statement is true
0018 else disp("B is a CONSTANT")
0019 end

Console Output:

Enter a number: 10
Enter a string e.g E,F, etc: E
"A is constant"
"B is string"
"A is of course a CONSTANT"
"B is of course a STRING"

General structure of if-elseif-else conditional statements are shown below:

If Condition-1 True then


Task-1
Task-2
---------
Elseif Condition-2 True then
Task-3
Task-4
---------
Elseif Condition-3 True then
Task-5
Task-6
---------
Else
Task(s) for if-all-above-conditions False
End

Example codes of if-elseif-else conditional statements are shown below:

SciNotes Code:

0001 clear
0002 clc
0003
0004 A = input('Please enter a number either 40 or 50 or some other
number: ', "string")//It is better to get the input as a string
0005 A=strtod(A)//conversion of string to a number
0006
0007 if (A == 40) then disp("The number is forty")
0008
0009 elseif (A == 50) then disp("The number is fifty")
0010
0011 else disp("The number is neither forty nor fifty") 0012
end

Console Output:

Please enter a number either 40 or 50 or some other number: 50


"The number is fifty"

Please enter a number either 40 or 50 or some other number: 37


"The number is neither forty nor fifty"
17 For Loops
When repeating tasks
By the end of this Section, you will be able in programming, loops
to… are used. For-End loop
is a common option.
1. Write executable codes using for-end
The general program
loops.
flow is shown in the
2. Write executable codes using nested for- following diagram.
end loops.
3. Use 'break' in a for-end loop.
Figure 16.1 Flow chart for a simple for-loop

Example code of for-end loop is shown below:

SciNotes Code:

0001 i=0//initial value of i


0002 k=0//initial value of k
0003
0004 // from 1 to 5
0005 //start-value:default increment 1[not entered]:end-value
0006 for i = 1:5
0007 disp(i)
0008 end
0009
0010 // from 1 to 5
0011 //start-value:increment 0.5:end-value:
0012 for k = 1:0.5:5
0013 disp(k)
0014 end

Console Output:

exec('/home/kalyansg/Dropbox/scilab-data/User-Input-010.sce', -1)

1.

2.

3.

4.

5.

1.

1.5

2.

2.5

3.

3.5
4.

4.5

5.

Two sets of values of output for two indexes i & k - 1 to 5 with increment 1
& 1 to 5 with increment 0.5

For Loops - Nested


Figure 16.2 Flow chart for a nested for-loop

Here, the inner loop [referring to the diagram - condition II - for_end loop 2]
does 2 tasks, which is repeated a number of times depending on the
requirements.
Assuming these repeated tasks are required for three different cases - done
by the outer loop 3 times [referring to the diagram - condition I - for_end
loop 1] .

Example code of for-end nested loop is shown below:

SciNotes Code:

0001 x=0 //initial value setting


0002 y1=0 //initial value setting
0003 y=0 //initial value setting
0004
0005 mprintf('\n\t x-value \t y-value \n\n') //Labels for the table
0006
0007 // nested loops
0008 // start : step : end
0009
0010 for x = 1:1:3 // 1, 2, 3 (three times)
0011 for y1 = 2:0.5:5 // 2, 3, 4, 5 (four times)
0012 y=y1/3 //some process - Task 1
0013 mprintf('\t %d \t\t%.3f\n',x,y) // 3x4 = 12 times - Task 2
0014 end
0015 end

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-011.sce', -1)

x-value y-value

1 0.667
1 0.833
1 1.000
1 1.167
1 1.333
1 1.500
1 1.667
2 0.667
2 0.833
2 1.000
2 1.167
2 1.333
2 1.500
2 1.667
3 0.667
3 0.833
3 1.000
3 1.167
3 1.333
3 1.500
3 1.667

Break in a for-end loop

Inside a for-loop, the command break forces the end of the loop. This
command may be required, as an example, while going through an array of
numbers, it is required to find when the array element exceeds a specified
value. This is shown in the following example.

SciNotes Code:

0001 // start : step : end


0002
0003 for i=1:1:5
0004 A(i)=i/10
0005 disp(A(i))
0006 end

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-012.sce', -1)


0.1
0.2
0.3
0.4
0.5

The 'break' parameter is now included in the SciNotes code:

0001 // start : step : end


0002
0003 for i=1:1:5
0004 A(i)=i/10 0005
if A(i)> 0.3 break end // when the array value exceeds 0.3
the program will break & end.
0006 disp(A(i))
0007 end

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-013.sce', -1)

0.1
0.2
0.3
18 While Loop

By the end of this Section, you will be able


to…
While-loop is also
1. Write executable codes using 'while'
frequently used and it
loops.
could be somewhat
2. Provide output for specified decimal easier to implement
places. than for-loop.
3. Use 'break' in a while loop. (“WHILE Loops – x-
Engineer.Org.”)
Figure 17.1 Flow chart for a typical while-loop

Example code of a typical while-loop is shown below:

SciNotes Code:

0001 i=1//initialise index


0002 while i<=5
0003 f(i)=i^2 + sqrt(i) //task-1
0004 disp(f(i)) //task-2
0005 i=i+1
0006 end

The first line initialises the index i (i = 1).


The second line defines the while-loop condition (x<=5).
The third and fourth lines are the two tasks and will be executed as long
as the while-loop condition is true.
In the fifth line, the index i is incremented by 1.
The sixth line will end the while-loop when the while-loop condition
becomes false.

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-014.sce', -1)

2.
5.4142136
10.732051
18.
27.236068

The formatting can be improved by a user-defined function as shown below:

SciNotes Code:

0001 function z=roundToDP(x, n) // "Rounding x to n decimal places"


0002
0003 z = x*(10^(n+1))
0004 z = z/10;
0005 z = round(z);
0006 z=z/(10^n);
0007
0008 endfunction

The following SciNotes code tries out the used-defined function


'roundToDP', which was saved as'roundToDP.sci' in the same working
directory. [User-defined functions will be explained later in a separate section
- this could be considered as a primer.]

0001 exec('roundToDP.sci');//loading the user-defined function


0002
0003 a = 10.456789
0004 b=roundToDP(a,3)
0005 disp(a,b)

Console Output - with precision of rounded 3 decimal point:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-015.sce', -1)

10.456789

10.457

Modifying the while-loop code in SciNotes:

0001 exec('roundToDP.sci');//loading the user-defined function


0002
0003 i=1//initialise index
0004 while i<=5
0005 f(i)=i^2 + sqrt(i)
0006 b=roundToDP(f(i),2) //output rounded to 2 decimal
places
0007 disp(b)
0008 i=i+1
0009 end

Console Output - with precision of rounded 2 decimal point:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-016.sce', -1)

2.
5.41
10.73
18.
27.24

'break' with while-loop:

SciNotes Code:

0001 a=input('Enter a number between 1 and 9: ')


0002
0003 i=1
0004
0005 while i <=5
0006 b=a*i^2
0007 disp(b)
0008 if b>80; // if b increases above 80, the while-loop
breaks
0009 disp('index i = '+string(i));
0010 break;
0011 end
0012 i=i+1
0013 end

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/User-Input-017.sce', -1)


Enter a number between 1 and 9: 8

8.

32.

72.

128.

"index i = 4"
The program breaks the while-loop when it reaches the given 'if-condition'.
19 Select Case Conditional Statements
While choosing from a
By the end of this Section, you will be able list of options, select-
to… case is considered a
better structure.
1. Write executable codes using select-case
(“SELECT CASE
conditional statements.
Conditional Statements
– x-Engineer.Org.”)

The general structure of the select-case is as shown below:


Select Case-name
Case 1
Task(s) for Case-1
Case 2
Task(s) for Case-2
Case 3
Task(s) for Case-3
------------------
Case n
Task(s) for Case-n
Else
Task(s) for exception
End

Example code of a typical while-loop is shown below:

SciNotes Code:

0001 clear
0002 clc
0003 month = 0;
0004
0005 while (month<1 | month>6) //Limits of entry set between minimum
- 1 and maximum - 6
0006
0007 month = input('Please choose your option between 1 and 6: ',
"string")//It is better to get the user input as a string
0008 month=strtod(month)//conversion of string to a number
0009 if (isnan(month)) then month = 0;end//nan-not a number,
isnan checks if the month is a nan, if it is a nan then month is allocated a
value of 0
0010 end
0011
0012 select month
0013 case 1
0014 disp("Month is January")
0015 case 2
0016 disp("Month is February")
0017 case 3
0018 disp("Month is March")
0019 case 4
0020 disp("Month is April")
0021 case 5
0022 disp("Month is May")
0023 case 6
0024 disp("Month is June")
0025 else
0026 disp("Wrong Month number")
0027
0028 end
0029
0030 disp("Your selected month number is: "+ string (month))

Lines 0005 to 0009 shows the codes for user-input and user-input-validation.
This is an important routine, which could be used while getting a numerical
input from a user. The routine takes care of user-input errors.

Console Output:

Please choose your option between 1 and 6: 5


"Month is May"

"Your selected month number is: 5"


20 Custom Functions
When there is a need to
By the end of this Section, you will be able define some routines,
to… which are frequently
needed and are not
1. Develop custom-function for two inputs
included as built-in
and one output.
functions in Scilab,
2. Develop custom-function for three inputs custom functions can
and output as a process (e.g. plotting a be created in SciNotes.
graph). These could then be
3. Develop on-line custom-functions. saved as files with the
extension '.sci' as
opposed to the
extension 'sce', which are normally used for storing programs in SciNotes.

The general structure of Scilab function code is shown below: (“Scilab


Functions and Scripts.”)

function [output list] = name(input list)


local variable and constant declarations
statements
endfunction

A function-object will have input variables (sometimes no input variable),


internal variables for procedures, and output variables. Of these, only output
variables are stored in the program.
Figure 20.1 Function Object in Scilab

An example of a single number input routine is shown as a function below.


The function includes the error-handling routines.

SciNotes Code:

0001 function [z]=SingleNumberInput(x1, x2)


0002
0003 z=0
0004 while z<x1 | z>x2 | z==0 // condition for while
0005 mprintf('Choose your option between %i,and %i',x1,x2) //
guiding the user
0006 z=input('Enter your option: ',"string") // user input in
string
0007 z=strtod(z);disp(z) // string to number
0008 if (isnan(z)) z=0;end // if no number is entered by mistake
0009 end
0010
0011 endfunction
The function is then saved in the working directory as SingleNumberInput.sci

It can be called anytime with following command:

--> exec('SingleNumberInput.sci');

The function could be applied with commands as shown below:

--> [r]=SingleNumberInput(10,15)
Choose your option between 10, and 15
Enter your option: 89
89.
Choose your option between 10, and 15
Enter your option: 9
9.
Choose your option between 10, and 15
Enter your option: 10
10.
r =
10.

Another 'function' application for plotting is shown below:

SciNotes Code:

0001 function [ ]=SinePlot(x1, d, x2)


0002
0003 x = x1 : d : x2;//start:step:end for graphing
0005 y = sin(x);
0007 plot(x, y, 'b*'); //b-blue & *-graph type
0009 xgrid
0010
0011 endfunction

Executing the 'function' at the console, it can be applied as shown below:

--> exec('SinePlot.sci');
--> SinePlot(0,0.1,15)

The graphic output is shown below:

Figure 20.2 Function 'SinePlot'

Defining online custom function

There is a command to define an online custom function in Scilab (“The


Fastest Way to Define a Function in Scilab – x-Engineer.Org.”).

Command 'deff' is defined as the 'in-line definition of a function' in Scilab.


Syntax for 'deff' is:

deff('[s1, s2, ...] = newfunction(e1, e2, ...)',text)

The arguments e1, e2, ... are input variables, while s1, s2, ... are the output
variables. 'text' would be character strings.
Assuming, there is a function ax^2 +bx + c, the following code shows the
online function definition. This is the case for multiple inputs and multiple
outputs.

--> deff('[x1,x2]=quadratic(a,b,c)',['m=sqrt(b^2-4*a*c)';'n1=(-
b+m)/(2*a)';'n2=(-b-m)/(2*a)';'x1=n1';'x2=n2'])

Screen Output: Shown for two cases with real and imaginary outputs.

--> [x1,x2]=quadratic(1,-7,12)
x1 =
4.
x2 =
3.

--> [x1,x2]=quadratic(4,3,6)
x1 =
-0.375 + 1.1659224i
x2 =
-0.375 - 1.1659224i

Checking which variables are stored after the operation, the following results
are found:

--> m
Undefined variable: m
--> n1
Undefined variable: n1
--> n2
Undefined variable: n2
--> a
Undefined variable: a
--> x1
x1 =
4.
--> x2
x2 =
3.
It checks out with variable browser report, shown below:

Figure 20.3 Variable Browser Output

So, only variables stored in the system are the output variables x1 & x2.
Others are all internal variables of the function and these variables can be
reused later in the program.

For a single input and a single output, the code will be as shown in the
following example:

--> deff('y=f(x)','y=5*x+3')

Screen Output:
--> f(3)
ans =
18.

For a multiple input and a single output, the code will be as shown in the
following example:

--> deff('y=myfct(a,b)','y=a*b^2')

Screen Output:
--> myfct(3,4)
ans =
48.

Scilab functions can be seen, perhaps, as black boxes as shown below:


21 Importing Data
Usually, shipboard data
By the end of this Section, you will be able is stored in spreadsheet
to… files. The common way
to transfer them into
1. Write an executable code to read a csv-
Scilab is using comma-
file.
separated values
2. Write an executable code to read a csv- (*.csv) file format.
file and assign a matrix variable. (“How to Import Table
3. Plot data from a csv file. Data (*.Csv) in
Scilab".)

Considering a simple spreadsheet file (see below):

A B
1 0
2 20
3 38
4 55
5 66
6 67
7 57
8 40
9 21
10 -5

This is saved as a csv file (either in MS Office or LibreOffice)


named, 'csvImport.csv' and moved to the working directory of Scilab.

The code to read the 'csvImport.csv' is shown below.

SciNotes Code:

0001 M=csvRead('csvImport.csv') // reading csv file


0002 disp(M)
0003
0004 col1=M(:,1)
0005 col2=M(:,2)
0006 plot(col1,col2,'b-','linewidth',2) // x-y plot - col1: x-values col2: y-
values
0007 xgrid

Console Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/Plot-from-Array-01.sce',
-1)

1. 0.
2. 20.
3. 38.
4. 55.
5. 66.
6. 67.
7. 57.
8. 40.
9. 21.
10. -5.

Also, there is a graphic plot output (shown below):


Figure 21.1 Plot of data imported using 'csvRead'
22 2D Plotting

By the end of this Section, you will be able Scilab has the two
to… following in-built
functions for x-y
1. Plot 2d graphs using both 'plot2d' and
plotting: (“Polyline
'plot' commands.
Properties -
2. Use polyline properties in the plots. Description of the
3. Provide 'titles', 'axes', 'legends' and control Polyline Entity
their fonts and use 'LaTeX' to write Properties.”)
equations.
4. Draw multiple plots in one window using
'subplot' command.

plot2d
plot

Syntax of plot2d is given below:

plot2d ([logflag,][x,],y[,style[,strf[,leg[,rect[,nax]]]]])

Optional Arguments:

logflag - It sets the scale either linear or logarithmic. Possible values


are "nn", "nl" , "ln" and "ll", where 'l' stands for logarithmic scale and 'n'
stands for normal scale.

style - It sets the line type. Positive integers are for continuous line (e.g 1-
black & 5-red). The negative integers are for the given curve points drawn
using marks as per the mark_style property given below.
strf - It is a string of length 3 "xyz" (by default strf= "081")

x - controls the display of captions.

x=0
no caption.
x=1
captions are displayed. They are given by the optional argument leg.

y - controls the computation of the actual coordinate ranges from the


minimal requested values. Actual ranges can be larger than minimal
requirements.

y=0
no computation, the plot use the previous (or default) scale
y=1
from the rect arg
y=2
from the min/max of the x, y data
y=3
built for an isometric scale from the rect arg
y=4
built for an isometric plot from the min/max of the x, y data
y=5
enlarged for pretty axes from the rect arg
y=6
enlarged for pretty axes from the min/max of the x, y data
y=7
like y=1 but the previous plot(s) are redrawn to use the new scale
y=8
like y=2 but the previous plot(s) are redrawn to use the new scale
z - controls the display of information on the frame around the plot. If axes
are requested, the number of tics can be specified by the nax optional
argument.

z=0
nothing is drawn around the plot.
z=1
axes are drawn, the y=axis is displayed on the left.
z=2
the plot is surrounded by a box without tics.
z=3
axes are drawn, the y=axis is displayed on the right.
z=4
axes are drawn centred in the middle of the frame box.
z=5
axes are drawn so as to cross at point (0,0). If point (0,0) does not lie
inside the frame, axes will not appear on the graph.

leg - This option may be used to sets the curve captions. It must be a string
with the form "leg1@leg2@...." where leg1 , leg2 , etc. are respectively the
captions of the first curve, of the second curve, etc. The default is " ".

rect - This option may be used to set the minimal bounds requested for the
plot. If this option is specified, the associated value should be a real vector
with four entries: [xmin,ymin,xmax,ymax]. xmin and xmax defines the
bounds on the abscissae while ymin and ymax defines the bounds on the
ordinates.

nax - This option may be used to specify the axes labels and tics definition.
The associated value should be a real vector with four integer entries
[nx,Nx,ny,Ny]. Nx gives the number of main tics to be used on the x-axis (to
use autoticks set it to -1), nx gives the number of subtics to be drawn between
two main x-axis tics. Ny and ny give similar information for the y-axis. If
axesflag option is not set nax option supposes that axesflag option has been
set to 9.

As the above are optional arguments, all of them need not be selected. The
following example shows a simplified selection.

Figure 22.1 Polyline Properties

SciNotes Code:

clear;//kills variables

clf();//clear graphic window


M=5;//Amplitude of y1
N=3;//Amplitude of y2

t = linspace (0,10,100);//t-min, t-max, divisions (more division ->


smoother)

y1 = M*sin(t);//define y1 in terms of t
y2 = N*sin(t);//define y2 in terms of t
plot2d (t,y1,style=-6, rect=[0,-6,10,6]);//plot t-y,style, define area
coordinates
plot2d (t,y2, style=5);
xgrid(2);//style;
xtitle("t-y Plot for 5sint & 3sint", "t Axis", "y Axis");//title, x-axis, y-axis
legend ("y1=5sint","y2=3sint",[4]);//legend for y1,y2,[legend location
options - 1/2/3/4]
clear;//kills variables

Graphic Window Output:


Figure 22.2 Plotting using 'plot2d'

Linspace - linearly spaced vector - minimum, maximum & divisions (x1, x2,
d) - bigger the value of d smoother will be the graph. Default value of d is
100.

The following example showing how to plot from an array.

SciNotes Code:

0001 clear;//kills variables


0002
0003 clf();//clear graphic window
0004
0005 t = linspace (0,12,12);//t-min, t-max, divisions
0006
0007 y1 = [0,20,45,75,85,88,84,77,55,33,19,0] // Array to be plotted
0008 y2 = [0,5,12,15,22,30,35,46,58,66,77,88] // Array to be plotted
0009
0010 plot2d (t,y1,style=6, rect=[0,0,13,100]);//plot t-y,style, define area
coordinates
0011 plot2d (t,y2, style=-11);
0012 xgrid // Draws the grid
0013 xtitle("t-y Plot for 5sint & 3sint", "t Axis", "y Axis");//title, x-axis,
y-axis
0014 legend ("y1-graph","y2-graph",2);//legend for y1,y2,location

Graphic Window Output:


Figure 22.3 Plotting from an array

The following example shows some of the additional capabilities of 'plot2d'


command of Scilab. The make the graphic output more presentable.

SciNotes Code:

0001 x=[-5+0.1:5]//x-range defined -5 to +5 and increment by 0.1


0002
0003 f1=x^2 +3*x +15//Function f1 defined
0004 f2=x^2-5*x-10//Function f2 defined
0005
0006 plot2d(x,f1,style=6)//Style 6 - red
0007 plot2d(x,f2,style=1)//Style 1 - black
0008
0009 xgrid(6) //Grid drawn with colour 6 - red
0010
0011 xtitle("2 Graphs - Functions of x","X #","Functions f1,f2 #")
0012 l1=legend(["$x^2+3x+15$";"$x^2-5x-10$"],5) // Legend-
equations defined within $-signs
0013 // If no $ sign it will be just strings
0014 // 5-Defines position of legend - for user to select location
0015 // Other fixed location options for legend - 1/2/3/4
0016 fz=gca() // This routine returns the handle of the current axes for
the current figure.
0017 fz.font_size=4 // Using the handle axis fontsize is increased
0018 fz.x_label.font_size=4 // Using the handle x-label fontsize is
increased
0019 fz.y_label.font_size=4
0020 fz.title.font_size=6
0021 l1.font_size=4//Legend font-size set to 4 (between 1 to 10)
0022 fz.thickness=1.5 // Using the handle all line-thicknesses are
increased

Graphic Window Output:


Figure 22.4 Better presentation with 'plot2d'

'plot' Command

'plot' command in Scilab is based on its use in the popular program


MATLAB. So, those with MATLAB-exposure can use plotting in Scilab
with ease. The following examples will be using 'plot' command instead of
'plot2d'.

The next example shows the printing of two 2-d graphs and the use of
'handle' to enhance a presentation. (“gcf - Return Handle of Current Graphic
Window.”)

SciNotes Code:

0001 x = [0:0.01:2*%pi];// pi in radian - equivalent to 180x2 or 360


degrees
0002
0003 y = sin(x);
0004 z = cos(x);
0005
0006 plot(x,y,'LineWidth',2) //Line thickness changed
0007
0008 plot(x,z,'r','LineWidth',2)
0009
0010 xgrid(2)// 2-blue grid-line colour
0011
0012 xlabel('x-axis','fontsize',4)
0013 ylabel('sin(x), cos(x)','fontsize',4)
0014 title('Plot of sin(x) and cos(x)','fontsize',6)
0015
0016 g = gcf();//Returns handle of current graphic window.
0017 L=legend(g, ['sin(x)';'cos(x)'],5);//5 is used to position at any point
on the graph
0018 //Other fixed positions are 1/2/3/4... -6 could bring it below the
graph
0019 L.font_size=3//Handle L is used increase the legend fontsize

Graphic Window Output:


Figure 22.5 'plot' command in Scilab

subplot - It is a command in Scilab when there is a need to put two or more


plots in one window. 'subplot, has the following syntax:

subplot(rows, columns, plot location)

For example, for two plots in one window, the first plot (on the left) will have
the command 'subplot(1,2,1)' and the second plot (on the right) will have the
command 'subplot(1,2,2)'. An example, showing the application is given
below.

SciNotes Code:

0001 // Subplot usage for plotting two plots in one window


0002
0003 clf() // Clear or reset a figure
0004 subplot(1,2,1)//row-1, column-2,1st plot position-left(1)
0005 x = [0:0.1:1]';
0006 y=x^2 ;
0007 plot(x,y,'Linewidth',2)//2 - line thickness
0008 ylabel("x^2",'fontsize',4)
0009 xlabel("X-Axis",'fontsize',4)
0010 xgrid (1)//gridline - black
0011 title('Subplot Example -Plot:1','fontsize',5)
0012 a=get("current_axes")//get the handle of the newly created axes
0013 a.axes_visible="on"; // makes the axes visible
0014 a.font_size=3; //set the tics label font size
0015
0016 // m varies between 0 and 2# in radian
0017 m = [0:0.1:2*%pi]';
0018 subplot(1,2,2)//row-1, column-2,2nd plot to the right(2)
0019 plot(m, sin(m),'Linewidth',2)//2 - line thickness
0020 xlabel("Values of m",'fontsize',4)
0021 ylabel("sin(m)",'fontsize',4)
0022 xgrid (6)//gridline - red
0023 title('Subplot Example -Plot:2','fontsize',5)
0024 b=get("current_axes")//get the handle of the newly created axes
0025 b.axes_visible="on"; // makes the axes visible
0026 b.font_size=3; //set the tics label font size

Graphic Window Output:


Figure 22.6 Subplot example

The next example shows six plots in a single window and is modified
from a stackoverflow aricle.
Some of the attributes of the four figures were changed to show how these
could be altered with relevant codes.

SciNotes Code:

0001 clf()
0002 figure;
0003 rand(10); // Seed for Random Number Generator
0004 subplot(2,3,1);
0005 x = rand(100,1);
0006 y = rand(100,1);
0007 plot(x,y,'b.');
0008 title('First plot','fontsize',4);
0009 subplot(2,3,2);
0010 x = rand(100,1);
0011 y = rand(100,1);
0012 plot(x,y,'r.');
0013 title('Second plot');
0014 a=get("current_axes")//get the handle of the newly created axes
0015 a.axes_visible="on"; // makes the axes visible
0016 a.font_size=3; //set the tics label font size
0017
0018 subplot(2,3,3);
0019 x = rand(100,1);
0020 y = rand(100,1);
0021 plot(x,y,'b.');
0022 title('Third plot','fontsize',4);
0023 subplot(2,3,4);
0024 x = rand(100,1);
0025 y = rand(100,1);
0026 plot(x,y,'g.');
0027 title('Fourth plot');
0028 subplot(2,3,5);
0029 x = rand(100,1);
0030 y = rand(100,1);
0031 plot(x,y,'b.');
0032 title('Fifth plot','fontsize',4);
0033 subplot(2,3,6);
0034 x = rand(100,1);
0035 y = rand(100,1);
0036 plot(x,y,'y.');
0037 title('Sixth plot');

Graphic Window Output:


Figure 22.7 Subplot - 6 images in one window

Using LaTeX to Write Equations

LaTeX can be used to write equations in Scilab. LaTeX format can be


obtained online at Latex Online. LaTeX equations could be entered within
two $ signs as shown in the code below:

SciNotes Code:

0001 x=[-2:0.1:0.4]//x-range defined -5 to +5 and increment by 0.1


0002
0003 f1=x^2 +3*x +15//Function f1 defined
0004 f2=(2*x-1)^-1//Function f2 defined
0005
0006 plot2d(x,f1,style=6)//Style 6 - red
0007 plot2d(x,f2,style=1)//Style 1 - black
0008
0009 xgrid(6) //Grid drawn with colour 6 - red
0010
0011 ylabel(["$\frac{1}{2x-1},
$","$X^2+3x+15$"],'fontsize',4,'color',1)
0012 xlabel("x-->",'fontsize',4,'color',1)
0013
0014 fz=gca()
0015 xtitle("Using LaTeX to Write Equations")
0016 fz.title.font_size=5
0017
0018 l1=legend(["$X^2+3x+15$";"$\frac{1}{2x-1}$"],5)
0019 l1.font_size=4

Graphic Window Output:


Figure 22.8 Using LaTeX in Scilab
23 Application Development

By the end of this Section, you will be able An application


to… development takes
more planning than
1. List out sequential development tasks for
while writing codes for
application development in Scilab.
short routines. Here, in
2. Break down a large programming task this section, a small
into smaller independent programs with application
specified inputs and outputs. development process
3. Combine the smaller programs into a will be shown covering
large workable Scilab code. drawing of 2-d graphs
from a common
4. Handle erroneous user inputs in a spreadsheet file (either
program. in Excel .xlsx /.xls or
LibreOffice .ods).

It is probably a good idea to write out the detailed objectives for the exercise
before writing codes to ensure that all aspects are taken care of during coding.

Development Tasks in Detail:

Task 1 - Prepare the spreadsheet file - While importing data into Scilab
only numerical values will be accepted. So, rows and columns with
strings (for example header rows and leftmost column with descriptions)
should be deleted. The file should also be saved in csv text-file format.
The file should then be brought into the working directory of Scilab.
Task 2 - Ask user for the 'csv' filename - Prompt user for the filename.
Read user-input as a string. Show the filename on the screen to get
confirmation from the user. If there is an error, go through the process
again. Read confirmed user-input and assign it to a variable. A flowchart
for the task is shown below and the code for this task is saved as a
function 'FileName.sci'.
Figure 23.1 FileName flowchart

SciNotes Code:

function [a]=FileName()
i=1;
while (i>0)
a=input('Enter the filename: ',"string");
disp(a);
n=input('Confirm filename Y/N: ',"string");
if n=="Y" then i=0;end
if n=="N" then disp ('Re-enter');i=1;end
end
disp('So,the filename is '+ string (a));
endfunction

Screen Output:

--> exec('/home/kalyansg/Dropbox/scilab-data/Graph-Drawing-
Application/FileName.sci', -1)
--> [a]=FileName()
Enter the filename: test
"test"
Confirm filename Y/N: N
"Re-enter"
Enter the filename: test
"test"
Confirm filename Y/N: Y
"So,the filename is test"
a =
"test"

Task 3 - Error Handling:

After this, the following command could be used to check if the file is
actually available at the working directory.

[fd,err]=mopen(a)
fd = 1. err = 0.

If the err=-2 then the file is not there and the program should stop and
user should be asked to recheck the name & location of the file.
Task 4 - Read csv-file as a matrix - Read the csv-file and assign a
variable to capture the data (as data type - double). Screen output is
shown below with the dummy data (10 rows x 6 columns), which is in
test.csv. Row and column sizes of the matrix are also ascertained at the
same time using the 'size' command.

--> a='test.csv'
a =
"test.csv"
--> exec('/home/kalyansg/Dropbox/scilab-data/Graph-Drawing-
Application/csv_FileOpen.sci', -1)
--> [b]=csv_FileOpen(a)
b =

315. 320. 335. 315. 340. 319.


313. 318. 330. 318. 338. 315.
310. 323. 325. 318. 336. 317.
309. 320. 324. 319. 336. 318.
307. 319. 330. 320. 320. 330.
305. 350. 335. 322. 310. 345.
307. 357. 335. 320. 302. 367.
308. 367. 330. 320. 300. 387.
308. 380. 328. 319. 300. 390.
309. 395. 330. 319. 295. 400.

--> [row,column]=size(b)
row =
10.
column =
6.

While presenting the matrix dat to user, there is a need to create index
column (while selecting row) and index row (while selecting column).
This is done using the following codes:

function [ ]=DisplayRow_Index()
a=[0+1:row]
dsi=a' //dsi-Display Row Index
//disp(dsi)
dsi_tb=[dsi,b]//dsi_tb - Display Row Index Table
disp(dsi_tb)
endfunction

function [ ]=DisplayColumn_Index()
a=[0+1:column]
dsi=a //dsi-Display Column Index
//disp(dsi)
dsi_tb=[dsi;b]//dsi_tb - Display Column Index Table
disp(dsi_tb)
endfunction

Screen Output: [Example for single-row option]

" You chose Option 1.Single row"


Confirm Option Y/N: y

1. 315. 320. 335. 315. 340. 319.


2. 313. 318. 330. 318. 338. 315.
3. 310. 323. 325. 318. 336. 317.
4. 309. 320. 324. 319. 336. 318.
5. 307. 319. 330. 320. 320. 330.
6. 305. 350. 335. 322. 310. 345.
7. 307. 357. 335. 320. 302. 367.
8. 308. 367. 330. 320. 300. 387.
9. 308. 380. 328. 319. 300. 390.
10. 309. 395. 330. 319. 295. 400.

Enter Row Number for your Graph

Choose your option between 0, and 10


Enter your option: 5

5.
307. 319. 330. 320. 320. 330.

Task 5 - Ask the user to choose an option for the graph - The following
options are to be presented:

a. singe row
b. single column
c. multi-row
d. multi-column
e. row vs column (for square matrix - not to be included in the
text)
f. column vs row (for square matrix - not to be included in the
text)

Option flowchart is similar to the FileName flowchart as shown below.


Scilab code for this function object is shown below.
Figure 23.2 Option flowchart

SciNotes Code:

function [op,c]=GraphOption()

disp('Choose your OPTION form the following')


disp('Option 1.Single row')
disp('Option 2.Single column')
disp('Option 3.Multi rows')
disp('Option 4.Multi columns')
disp('Option 5.Row vs. column')
disp('Option 6.Column vs row')

op = 0;
while (op<1 | op>6)

op = input('Please chose your option between 1 and 6: ');

if op==1 then c="You chose Option 1.Single row"


elseif op==2 then c="You chose Option 2.Single
column"
elseif op==3 then c="You chose Option 3.Multi-
rows"
elseif op==4 then c="You chose Option 4.Multi-
columns"
elseif op==5 then c="You chose Option 5.Row vs
column"
elseif op==6 then c="You chose Option 6.Column
vs row"
end

disp(op,c);
n=input('Confirm Option Y/N: ',"string");
if n=="Y" then end
if n=="N" then disp ('Re-enter');op=0;end

end//end while
endfunction

Screen Output:

--> exec('GraphOption.sci');
--> [op,c]=GraphOption()

"Choose your OPTION form the following"

"Option 1.Single row"


"Option 2.Single column"
"Option 3.Multi rows"
"Option 4.Multi columns"
"Option 5.Row vs. column"
"Option 6.Column vs row"

Please choose your option between 1 and 6: 3


3.
"You chose Option 3.Multi-rows"
Confirm Option Y/N: N
"Re-enter"
Please choose your option between 1 and 6: 4
4.
"You chose Option 4.Multi-columns"
Confirm Option Y/N: Y
op =
4.
c =
"You chose Option 4.Multi-columns"

Task 6 - Select Case to do the plotting - This is the final step of the
application, where the actual plotting is done with some interaction with
users. Select Case command is used to go through the six options,
defined earlier.

While coding the plotting routine the following is likely to be


encountered if the normal command of xgrid is used. The relevant
SciNotes codes are shown below. The commands which are deactivated
(// - in bold) are required to do a grid that is more relevant in this
particular situation. Two different outputs are shown below for
comparison.
exec('SingleNumberInput.sci');
a='test.csv';
i=0;
op=1;
row=10;
column=6;
exec('csv_FileOpen.sci');
[b]=csv_FileOpen(a);

select op
case 1 then

mprintf('Enter Row Number for your Graph\n')


[z]=SingleNumberInput(0, row);//A function within function
x = linspace (1,column,column);//x-min, x-max, divisions-
does not mean gaps-means ordinates
y = b(z,:)
disp(y);
clf();
plot2d(x,y)
xgrid(6) // This is the normal command for grid
fz=gca() // This routine returns the handle of the current
axes for the current figure.
fz.thickness=1.5 // Using the handle all line-thicknesses are
increased
//fz.grid=[1 1]
//tmp=fz.x_ticks
//tmp.locations=[0:6]
//tmp.labels=string(tmp.locations);
//fz.x_ticks=tmp;
xs2png(0,'Plot-01.png');

disp('Plot saved as Plot-01.png')


case 2 then
disp("which column counting from 1? ")
Figure 23.3 Plot with the normal 'xgrid' command
Figure 23.4 Plot with the 'x_ticks' command

File Save: A routine should be done to save the file. Before that the user
should be given an option for the file name. The following function-
object is created for this purpose.

SciNotes Code:

function [fs]=FileSave()
i=1;
while (i<>0)
fs=input('Enter the filename [e.g. Plot-01.png] for saving
your plot: ',"string");
disp(fs);
if (isfile(fs)) then disp("Filename already there in working
directory: Overwrite - Y New name - N");end
n=input('Confirm filename Y/N: ',"string");
if n=="Y" | n=="y" then i=0;end
if n=="N" | n=="n" then disp ('Re-enter');i=1;end
end

endfunction

Then in the main program:

//File-saving routine
exec('FileSave.sci');
[fs]=FileSave();
xs2png(0,fs);//saving plot with the user-given filename saved with
variable fs
//format - xs2png(win_num, file_name)...win_num - an
integer, ID of the figure to export.
mprintf('Plot saved as %s',fs)

Screen Output:
--> exec('/home/kalyansg/Dropbox/scilab-data/Graph-Drawing-
Application/2dPlot-SlectCase.sci', -1)
Enter Row Number for your Graph
Choose your option between 0,and 10
Enter your option: 4
4.
309. 320. 324. 319. 336. 318.
Enter your text for Title
Enter your text: Plot of Row-4
"Plot of Row-4"
Confirm text Y/N: y
Enter your text for X-Axis
Enter your text: X-Axis
"X-Axis"
Confirm text Y/N: y
Enter your text for Y-Axis
Enter your text: Y-Axis
"Y-Axis"
Confirm text Y/N: y
Enter your text for Legends
Enter your text: Row-4
"Row-4"
Confirm text Y/N: y
Enter the filename [e.g. Plot-01.png] for saving your plot: aa.png
"aa.png"
Confirm filename Y/N: y
Plot saved as aa.png
Figure 23.5 Polyline property and thickness changed

The following code shows the completed code for polyline control for the
above figure (Fig. 23.5). The relevant code lines are boldened.

select op
case 1 then

mprintf('Enter Row Number for your Graph\n')


[z]=SingleNumberInput(0, row);//A function within function
x = linspace (0,column,column);//x-min, x-max, divisions
y = b(z,:)
disp(y);
clf();
plot2d(x,y,6)
//xgrid(6)
fz=gca() // This routine returns the handle of the current axes for
the current figure.
fx=gcf(); //Returns handle of current graphic window.
fz.thickness=1.5 // Using the handle all line-thicknesses are
increased
fz.grid=[1 1]
tmp=fz.x_ticks
tmp.locations=[0:column]
tmp.labels=string(tmp.locations);
fz.x_ticks=tmp;
fx.children.children(1).children.line_style = 5;
fx.children.children(1).children.thickness = 3;

//Text Input for Title


mprintf('Enter your text for Title\n')
exec('TextInput.sci');
[txt_title]=TextInput()

//Text Input for X-Axis


mprintf('Enter your text for X-Axis\n')
[x_axis]=TextInput()

//Text Input for Y-Axis


mprintf('Enter your text for Y-Axis\n')
[y_axis]=TextInput()

//Text Input for Legend


mprintf('Enter your text for Legends\n')
[l]=TextInput()

xtitle([txt_title],[x_axis],[y_axis])
l1=legend([l],5)
fz.font_size=4 // Using the handle axis fontsize is increased
fz.x_label.font_size=4 // Using the handle x-label fontsize is
increased
fz.y_label.font_size=4
fz.title.font_size=6
l1.font_size=4//Legend font-size set to 4 (between 1 to 10)
//File-saving routine
exec('FileSave.sci');
[fs]=FileSave();
xs2png(0,fs);//saving plot with the user-given filename saved with
variable fs
//format - xs2png(win_num, file_name)...win_num - an
integer, ID of the figure to export.
mprintf('Plot saved as %s',fs)

The above code is used for the 'select-case-1', which is for plotting a
particular row of a matrix. When it comes to 'select-case-2', which is for
plotting a particular column, the code should be the same except that the
selection should be for columns, and the limit for the x-axis will also change.
The relevant codes are shown below:

y = b(z,:)//for row selection - 'select-case-1'


y = b(:,z)//for column selection - 'select-case-2'

x = linspace (0,column,column);//x-min, x-max, divisions -


'select-case-1' - for row-plotting select column
x = linspace (0,row,row);//x-min, x-max, divisions - 'select-
case-2'- for column-plotting slect row

The complete 'select-case-2 code is given below.

Scilab Code:

case 2 then
mprintf('Enter Column Number for your Graph\n')
[z]=SingleNumberInput(0, column);//A function within function
x = linspace (0,row,row);//x-min, x-max, divisions
y = b(:,z)//for column selection
disp(y);
clf();
plot2d(x,y)
//xgrid(6)
fz=gca() // This routine returns the handle of the current axes for
the current figure.
fx=gcf();
fz.thickness=1.5 // Using the handle all line-thicknesses are
increased
fz.grid=[1 1]
tmp=fz.x_ticks
tmp.locations=[0:row]
tmp.labels=string(tmp.locations);
fz.x_ticks=tmp;
fx.children.children(1).children.line_style = 4;
fx.children.children(1).children.thickness = 4;

//Text Input for Title


mprintf('Enter your text for Title\n')
exec('TextInput.sci');
[txt_title]=TextInput()

//Text Input for X-Axis


mprintf('Enter your text for X-Axis\n')
[x_axis]=TextInput()

//Text Input for Y-Axis


mprintf('Enter your text for Y-Axis\n')
[y_axis]=TextInput()

//Text Input for Legend


mprintf('Enter your text for Legends\n')
[l]=TextInput()

xtitle([txt_title],[x_axis],[y_axis])
l1=legend([l],5)
fz.font_size=4 // Using the handle axis fontsize is increased
fz.x_label.font_size=4 // Using the handle x-label fontsize is
increased
fz.y_label.font_size=4
fz.title.font_size=6
l1.font_size=4//Legend font-size set to 4 (between 1 to 10)

//File-saving routine
exec('FileSave.sci');
[fs]=FileSave();
xs2png(0,fs);//saving plot with the user-given filename saved with
variable fs
//format - xs2png(win_num, file_name)...win_num
- an integer, ID of the figure to export.
mprintf('Plot saved as %s',fs)

For 'select-case-3', which is for multi-row plotting, the code would quite
different. The input from the user has to capture an unknown number of
inputs. So, a row vector is used for user-input. The relevant code is shown
below:

Scilab Code:

i=1;
while (i<>0)
rs=input('Enter rows for plotting, e.g. [3,4,7] for Row-3,
Row-4 & Row-7 Your Choice: ')
disp(rs);
n=input('Confirm text Y/N: ',"string");
if n=="Y" | n=="y" then i=0;end
if n=="N" | n=="n" then disp ('Re-enter');i=1;end
end

For 'select-case-4', which is for multi-column plotting, the code would very
similar to case-3. Case-5 and case-6 are not covered in the text. These cases
are exclusively for square matrix, where the number of rows equal the
number of columns. These are left as exercises for the reader.

Complete Scilab Code for the Application:

001 clc
002 clearglobal();
003 clear();
004 clf();
004 close;
005
006 mprintf('\n\n ==== Matrix 2D Plot Utility Version 0.4
====\n\nEnter matrix filename to start.\n')
007
008 exec('SingleNumberInput.sci');
009 exec('FileName.sci');
010
011 [a]=FileName();
012 exec('csv_FileOpen.sci');
013 [b]=csv_FileOpen(a);
014 [row,column]=size(b);
015 i=0;
016 exec('GraphOption.sci');
017 [op,c]=GraphOption();
018
019
020 select op
021 case 1 then
022 exec('DisplayRow_Index.sci');
023 DisplayRow_Index();
024 mprintf('\n Enter Row Number for your Graph\n\n')
025 [z]=SingleNumberInput(0, row);//A function within function
026 x = linspace (1,column,column);//x-min, x-max, divisions
027
028 y = b(z,:)//for row selection
029 disp(y);
030 clf();
031 plot2d(x,y,5)
032 //xgrid(6)
033 fz=gca() // This routine returns the handle of the current axes
for the current figure.
034 fx=gcf();
035 fz.thickness=1.5 // Using the handle all line-thicknesses are
increased
036 fz.grid=[1 1]
037 tmp=fz.x_ticks
038 tmp.locations=[0:column]
039 tmp.labels=string(tmp.locations);
040 fz.x_ticks=tmp;
041 fx.children.children(1).children.line_style = 5;
042 fx.children.children(1).children.thickness = 4;
043
044 //Text Input for Title
045 mprintf('Enter your text for Title\n')
046 exec('TextInput.sci');
047 [txt_title]=TextInput()
048 if isempty(txt_title)
049 row_number=string(z)
050 plot_title='Plot for Row-'+row_number
051 txt_title=plot_title//default title
052 end
053
054 //Text Input for X-Axis
055 mprintf('Enter your text for X-Axis\n')
056 [x_axis]=TextInput()
057 if isempty(x_axis)
058 x_axis="X-Axis"
059 end
060
061 //Text Input for Y-Axis
062 mprintf('Enter your text for Y-Axis\n')
063 [y_axis]=TextInput()
064 if isempty(y_axis)
065 y_axis="Y-Axis"
066 end
067
068 //Text Input for Legend
069 mprintf('Enter your text for Legends\n')
070 [l]=TextInput()
071 if isempty(l)
072 default_legend='Row-'+row_number
073 l=default_legend
074 end
075
076 xtitle([txt_title],[x_axis],[y_axis])
077 l1=legend([l],5)
078 fz.font_size=4 // Using the handle axis fontsize is increased
079 fz.x_label.font_size=4 // Using the handle x-label fontsize is
increased
080 fz.y_label.font_size=4
081 fz.title.font_size=6
082 l1.font_size=4//Legend font-size set to 4 (between 1 to 10)
083
084 //File-saving routine
085 exec('FileSave.sci');
086 [fs]=FileSave();
087 xs2png(0,fs);//saving plot with the user-given filename saved
with variable fs
088 //format - xs2png(win_num, file_name)...win_num - an
integer, ID of the figure to export.
089 mprintf('Plot saved as %s',fs)
090
091 case 2 then
092 exec('DisplayColumn_Index.sci');
093 DisplayColumn_Index();
094 mprintf('\nEnter Column Number for your Graph\n\n')
095 [z]=SingleNumberInput(0, column);//A function within
function
096 x = linspace (1,row,row);//x-min, x-max, divisions
097 y = b(:,z)//for column selection
098 disp(y);
099 clf();
100 plot2d(x,[y],style=[color("red")])
101 //plot2d(x,[sin(x),cos(x)],style=[color("red"),color("green")]);
102 //xgrid(6)
103 fz=gca() // This routine returns the handle of the current axes
for the current figure.
104 fx=gcf();
105 fz.thickness=1.5 // Using the handle all line-thicknesses are
increased
106 fz.grid=[1 1]
107 tmp=fz.x_ticks
108 tmp.locations=[0:row]
109 tmp.labels=string(tmp.locations);
110 fz.x_ticks=tmp;
111 fx.children.children(1).children.line_style = 3;
112 fx.children.children(1).children.thickness = 3;
113
114 //Text Input for Title
115 mprintf('Enter your text for Title\n')
116 exec('TextInput.sci');
117 [txt_title]=TextInput()
118 if isempty(txt_title)
119 column_number=string(z)
120 plot_title='Plot for Column-'+column_number
121 txt_title=plot_title//default title
122 end
123
124 //Text Input for X-Axis
125 mprintf('Enter your text for X-Axis\n')
126 [x_axis]=TextInput()
127 if isempty(x_axis)
128 x_axis="X-Axis"
129 end
130
131 //Text Input for Y-Axis
132 mprintf('Enter your text for Y-Axis\n')
133 [y_axis]=TextInput()
134 if isempty(y_axis)
135 y_axis="Y-Axis"
136 end
137
138 //Text Input for Legend
139 mprintf('Enter your text for Legends\n')
140 [l]=TextInput()
141 if isempty(l)
142 default_legend='Column-'+column_number
143 l=default_legend
144 end
145
146 xtitle([txt_title],[x_axis],[y_axis])
147 l1=legend([l],5)
148 fz.font_size=4 // Using the handle axis fontsize is increased
149 fz.x_label.font_size=4 // Using the handle x-label fontsize is
increased
150 fz.y_label.font_size=4
151 fz.title.font_size=6
152 l1.font_size=4//Legend font-size set to 4 (between 1 to 10)
153
154 //File-saving routine
155 exec('FileSave.sci');
156 [fs]=FileSave();
157 xs2png(0,fs);//saving plot with the user-given filename saved
with variable fs
158 //format - xs2png(win_num, file_name)...win_num - an
integer, ID of the figure to export.
159 mprintf('Plot saved as %s',fs)
160
161 case 3 then
162
163 mprintf('\n== Multi-row Plotting ==\n\n');
164 exec('DisplayRow_Index.sci');
165 DisplayRow_Index();
166 mprintf('\n');
167
167 i=1;
168 while (i<>0)
169 rs=input('Enter rows for plotting, e.g. [3,4,7] for Row-3,
Row-4 & Row-7 Your Choice: ')
170 disp(rs);
171 n=input('Confirm text Y/N: ',"string");
172 if n=="Y" | n=="y" then i=0;end
173 if n=="N" | n=="n" then disp ('Re-enter');i=1;end
174 end
175
176 x=[0+1:column]
177 L_rs=length(rs)
178 for i=1:L_rs
179 r(i)=rs(:,i)
180 //disp(r(i))
181 y = b(r(i),:)
182 plot(x,y,'color',rand(1,3),'LineWidth',2)
183 j(i)=string(r(i))
184 j(i)='Row-'+j(i)
185 //disp(j(i))
186 xgrid
187
188 title('Multi-plot of Rows','fontsize',6)
189 xlabel('X-Axis','fontsize',4)
190 ylabel('Y-Axis','fontsize',4)
191 end
192
193 L1=legend(j,5)
194 L1.font_size=3;
195 fntsz = gca();// Activate the handle "Axes"
196 // display the properties of the handle "Axes"
197 fntsz.font_size = 3; //controlling fontsize of axes
198
199 //File-saving routine
200 exec('FileSave.sci');
201 [fs]=FileSave();
202 xs2png(0,fs);//saving plot with the user-given filename saved
with variable fs
203 //format - xs2png(win_num, file_name)...win_num - an
integer, ID of the figure to export.
204 mprintf('Plot saved as %s',fs)
205
206 case 4 then
207 mprintf('\n== Multi-column Plotting ==\n\n');
208 exec('DisplayColumn_Index.sci');
209 DisplayColumn_Index();
210 mprintf('\n');
211
212 i=1;
213 while (i<>0)
214 cs=input('Enter column for plotting, e.g. [1,2,4] for
Column-1, Column-2 & Column-4 Your Choice: ')
215 disp(cs);
216 n=input('Confirm text Y/N: ',"string");
217 if n=="Y" | n=="y" then i=0;end
218 if n=="N" | n=="n" then disp ('Re-enter');i=1;end
219 end
220
221 x=[0+1:row]
222 L_cs=length(cs)
223
224 for i=1:L_cs
225 cc(i)=cs(:,i)
226 y=b(:,cc(i))
227 plot(x,y','color',rand(1,3),'LineWidth',2)//Need to
transpose one of the arrays,
228 //to make them identical in
dimensions
229 j(i)=string(cc(i))
230 j(i)='Column-'+j(i)
231 //disp(j(i))
232 xgrid
233
234 title('Multi-plot of Columns','fontsize',6)
235 xlabel('X-Axis','fontsize',4)
236 ylabel('Y-Axis','fontsize',4)
237 end
238
239 L1=legend(j,5)
240 L1.font_size=3;
241 fntsz = gca(); // Activate the handle "Axes"
242 // display the properties of the handle "Axes"
243 fntsz.font_size = 3; //controlling fontsize of axes
244
245 //File-saving routine
246 exec('FileSave.sci');
247 [fs]=FileSave();
248 xs2png(0,fs);//saving plot with the user-given filename saved
with variable fs
249 //format - xs2png(win_num, file_name)...win_num - an
integer, ID of the figure to export.
250 mprintf('Plot saved as %s',fs)
251
252
253 case 5 then
254 disp("This works with a square matrix - not included in the
text - left as an exercise for the reader")
255 case 6 then
256 disp("This works with a square matrix - not included in the
text - left as an exercise for the reader")
257 else
258 error("Error")
259 end

Functions used in the program

The following functions are used in the above application:

1. SingleNumberInput.sci

function [z]=SingleNumberInput(x1, x2)

z=0
while z<x1 | z>x2 | z==0 // condition for while
mprintf('Choose your option between %i,and %i',x1,x2) //
guiding the user
z=input('Enter your option: ',"string") // user input in string
z=strtod(z);disp(z) // string to number
if (isnan(z)) z=0;end // if no number is entered by mistake
end

endfunction

2. FileName.sci

function [a]=FileName()
i=1;
while (i>0)
a=input('Enter the filename: ',"string");
disp(a);
n=input('Confirm filename Y/N: ',"string");
if n=="Y" | n=="y" then i=0;end
if n=="N" | n=="n" then disp ('Re-enter');i=1;end
end
disp('So,the filename is '+ string (a));
[fd,err]=mopen('a');
if err==0 then disp('good');end

endfunction

3. csv_FileOpen.sci

function [b]=csv_FileOpen(a)
b=csvRead(a)
endfunction

4. GraphOption.sci

function [op,c]=GraphOption()

disp(' Choose your OPTION form the following')

mprintf('\n Option 1.Single row\n\n')


mprintf(' Option 2.Single column\n\n')
mprintf(' Option 3.Multi rows\n\n')
mprintf(' Option 4.Multi columns\n\n')
mprintf(' Option 5.Row vs. column[for Square Matrix] - not
included\n\n')
mprintf(' Option 6.Column vs row [for Square Matrix] - not
included\n\n\n')

op = 0;
while (op<1 | op>6)

op = input(' Please chose your option between 1 and 6: ');

if op==1 then c=" You chose Option 1.Single row"


elseif op==2 then c=" You chose Option 2.Single
column"
elseif op==3 then c=" You chose Option 3.Multi-rows"
elseif op==4 then c=" You chose Option 4.Multi-
columns"
elseif op==5 then c=" You chose Option 5.row vs row"
elseif op==6 then c=" You chose Option 6.column vs
column"
end

disp(op,c);
n=input(' Confirm Option Y/N: ',"string");
if n=="Y" then end
if n=="N" then disp (' Re-enter');op=0;end

end//end while
endfunction

5. DisplayRow_Index.sci

function [ ]=DisplayRow_Index()
a=[0+1:row]
dsi=a' //dsi-Display Row Index
//disp(dsi)
dsi_tb=[dsi,b]//dsi_tb - Display Row Index Table
disp(dsi_tb)
endfunction

6. TextInput.sci

function [txt]=TextInput()
i=1;
while (i<>0)
txt=input('Enter your text or {Return} for default]:
',"string");

if txt=="" then i=0;end;

while (i<>0)
disp(txt);
n=input('Confirm text Y/N: ',"string");
if n=="Y" | n=="y" then i=0;end
if n=="N" | n=="n" then disp ('Re-enter');i=1;end
end
end
endfunction

7. FileSave.sci

function [fs]=FileSave()
i=1;
while (i<>0)
fs=input('Enter the filename [e.g. Plot-01.png] for saving
your plot: ',"string");
disp(fs);
if (isfile(fs)) then disp("Filename already there in working
directory: Overwrite - Y New name - N");end
n=input('Confirm filename Y/N: ',"string");
if n=="Y" | n=="y" then i=0;end
if n=="N" | n=="n" then disp ('Re-enter');i=1;end
end
endfunction
8. DisplayColumn_Index.sci

function []=DisplayColumn_Index()
a=[0+1:column]
dsi=a //dsi-Display Column Index
//disp(dsi)
dsi_tb=[dsi;b]//dsi_tb - Display Column Index Table
disp(dsi_tb)
endfunction

Screen Output for the Application

Two cases are shown 1) Single-row Plotting and 2) Multiple-column Plotting

1) Single-Row Plotting:

==== Matrix 2D Plot Utility Version 0.4 ====

Enter matrix filename to start.


Enter the filename: test.csv

"test.csv"
Confirm filename Y/N: y

"So, the filename is test.csv"

" Choose your OPTION form the following"

Option 1.Single row

Option 2.Single column

Option 3.Multi rows


Option 4.Multi columns

Option 5.Row vs. column[for Square Matrix] - not included

Option 6.Column vs row [for Square Matrix] - not included

Please choose your option between 1 and 6: 1

1.

" You chose Option 1.Single row"


Confirm Option Y/N: y

1. 315. 320. 335. 315. 340. 319.


2. 313. 318. 330. 318. 338. 315.
3. 310. 323. 325. 318. 336. 317.
4. 309. 320. 324. 319. 336. 318.
5. 307. 319. 330. 320. 320. 330.
6. 305. 350. 335. 322. 310. 345.
7. 307. 357. 335. 320. 302. 367.
8. 308. 367. 330. 320. 300. 387.
9. 308. 380. 328. 319. 300. 390.
10. 309. 395. 330. 319. 295. 400.

Enter Row Number for your Graph

Choose your option between 0,and 10


Enter your option: 5

5.

307. 319. 330. 320. 320. 330.


Enter your text for Title
Enter your text or {Return} for default]:

Enter your text for X-Axis


Enter your text or {Return} for default]:

Enter your text for Y-Axis


Enter your text or {Return} for default]:

Enter your text for Legends


Enter your text or {Return} for default]:

Enter the filename [e.g. Plot-01.png] for saving your plot: aa.png

"aa.png"

"Filename already there in working directory: Overwrite - Y


New name - N"
Confirm filename Y/N: y

Plot saved as aa.png


Figure 23.6 Single-row plotting

2) Multiple-Column Plotting:

==== Matrix 2D Plot Utility Version 0.4 ====

Enter matrix filename to start.


Enter the filename: test.csv

"test.csv"
Confirm filename Y/N: y
"So, the filename is test.csv"

" Choose your OPTION form the following"

Option 1.Single row

Option 2.Single column

Option 3.Multi rows

Option 4.Multi columns

Option 5.Row vs. column[for Square Matrix] - not included

Option 6.Column vs row [for Square Matrix] - not included

Please choose your option between 1 and 6: 4

4.

" You chose Option 4.Multi-columns"


Confirm Option Y/N: y

== Multi-column Plotting ==

1. 2. 3. 4. 5. 6.
315. 320. 335. 315. 340. 319.
313. 318. 330. 318. 338. 315.
310. 323. 325. 318. 336. 317.
309. 320. 324. 319. 336. 318.
307. 319. 330. 320. 320. 330.
305. 350. 335. 322. 310. 345.
307. 357. 335. 320. 302. 367.
308. 367. 330. 320. 300. 387.
308. 380. 328. 319. 300. 390.
309. 395. 330. 319. 295. 400.

Enter column for plotting, e.g. [1,2,4] for Column-1, Column-2 &
Column-4 Your Choice: [2,4,6]

2. 4. 6.
Confirm text Y/N: y

Enter the filename [e.g. Plot-01.png] for saving your plot: aa.png

"aa.png"

"Filename already there in the working directory: Overwrite - Y


New name - N"
Confirm filename Y/N: y

Plot saved as aa.png


Figure 23.7 Multiple-column plotting
24 XCOS Simulations

By the end of this Section, you will be able Simulation is useful in


to… engineering to study
what-if behaviours of
1. Use Xcos to simulate the response of a
real-world systems.
simple first-order system (with a given
The following diagarm,
transfer function) subject to unit step.
modified from Leros
2. Use Xcos to simulate the response of a and Andreatos, “Using
simple first-order system (with a given Xcos as a Teaching
transfer function) subject to a ramp input. Tool in a Simulation
3. State that control system analysis is easier Course”, shows an
when the system is analysied in the application of
frequency domain when XCOS simulator simulation, which
could be used. could be used to
improve a system
model. Additionally,
simulations could be used for validation of analytic modeling, which are
frequently developed with assumptions for simplification.

Figure 24.1 Role of simulation


For modeling and simulation, Scilab has a toolbox, called XCOS. XCOS
could be used for dynamic simulation of both continuous and discrete
systems. Xcos can also be used for data visualization and algebraic
operations. (x-engineer.org, “Introduction to Xcos – x-Engineer.Org.”)

To show some examples of XCOS for use on control systems, one needs to
understand the term 'transfer function'. (“How to Find the Transfer Function
of a System – x-Engineer.Org.”)

A 'transfer function', in this context, could be seen as ratio of the amplitude of


the output to the frequency of the input signal. Normally, we look at a system
in the time domain, where inputs and outputs change with respect to time(t).

Figure 24.2 Control System in time-domain

In the time-domain (t), systems are represented by ordinary differential


equations. Solving these differential equations are more difficult than if one
analyses the system using the frequency domain (s), which only deals with
algebraic manipulations. These two viewpoints are shown in the following
diagram.
Figure 24.3 Control system seen from time and frequency domains

The transfer function is defined as the ratio of the output and the input in the
Laplace domain, which is a mathematical domain where, instead of viewing
processes in the time domain, the processes are viewed as equations in the
frequency domain. Laplace domain is viewed in what is called a 's-plane'.

Hence, the transfer function G(s), considered as the dynamic characteristics


of the system, is expressed as follows in the s-plane:
Figure 24.4 System transfer function in the s-domain

In this section, to show examples of XCOS-simulation capabilities, only first-


order systems would be considered.
Examples of first-order systems include cooling/heating systems, R-C
electrical circuits, the flow of fluid from a tank, braking system for an
automobile, etc. First-order systems have typically one independent energy
storage element. The general form of the first-order differential equation is as
follows:

Dividing both sides by a,


1/a is known as the 'time-constant' τ of the system, whereas KDC is known as
the 'DC gain'.

The first-order system can be re-written as:

Now, the above equation should be transferred to the Laplace domain. (see
Duffy, “Laplace Transform of a First Order System.”)

Hence, the 1st order transfer function is given by the following.

Once the transfer function of the system is known, the system can be
simulated in XCOS. (see Yaqub, An Introduction to Xcos.)
The XCOS is set up as shown in the diagram: (Yaqub, Making Your First
Simulation in Scilab Xcos [Unit Step Response]).

Figure 24.5 Step response of a first-order system

The following blocks from the Palette browser are used (dragged, dropped
and connected) in the above set up:

1. Continuous Time Systems →CLR Block (Transfer function block)


2. Sources →Step_Function Block (To provide a step input to the system)
3. Sinks →CSCOPE Block (To provide the display)
4. Event handling →CLOCK_c Block (To trigger the event capture)

Block parameters are set as follows:


Figure 24.6 Parameter-setting for XCOS simulation

The following diagram shows an example of a ramp-input simulation in


XCOS for a first-order system.
Figure 24.7 Ramp input simulation in XCOS for a first-order system

This is just an introduction to XCOS simulation and more applications of


XCOS will be covered in the subsequent volumes of the series.
VII Bibliography
Ariba, Yassine. “Introduction to Scilab - Application to Feedback Control.”
Brno University of Technology, April 2014, 154. Link to pdf

“Array Data Structure.” In Wikipedia, March 20, 2020. Wikipedia-Link

“Display Data in Scilab Using the mprintf() Function – x-Engineer.Org.”


Accessed April 10, 2020. x-Engineer-Link

Duffy, Gavin. “Laplace Transform of a First Order System.” Accessed May


17, 2020. Dublin-Institute-of-Technology-Link

“Open Source | www.Scilab.Org.” n.d. Accessed March 23, 2020. Scilab-


Site-Link

Hardesty, Larry. 2013. “Explained: Matrices - MIT News.” Explained:


Matrices. December 6, 2013. MIT-News-Link

“How to Display a Table in Scilab with Mprintf() Function – x-


Engineer.Org.” Accessed April 11, 2020. x-Engineer-Link

“How to Find the Transfer Function of a System – x-Engineer.Org.”


Accessed May 17, 2020. x-Engineer-Link

“How to Import Table Data (*.Csv) in Scilab – x-Engineer.Org.” Accessed


April 18, 2020. x-Engineer-Link

“Introduction to Xcos – x-Engineer.Org.” Accessed May 15, 2020. x-


Engineer-Link

Leros, A., and Antonios S. Andreatos. “Using Xcos as a Teaching Tool in a


Simulation Course.” ResearchGate, March 2012. Researchgate Link

Nagar, Sandeep. Introduction to Scilab: For Engineers and Scientists. 1st ed.
edition. New York, NY: Apress, 2017. Amazon Link
“Polyline Properties - Description of the Polyline Entity Properties.”
Accessed May 6, 2020. Scilab Help Link

“Scilab 6.1.0 | Www.Scilab.Org.” Accessed May 18, 2020. Scilab-Link

“Scilab Functions and Scripts.” Accessed April 17, 2020. Matrixlab-Link

Scilab Online Help - gcf. “Gcf - Return Handle of Current Graphic Window.”
Scilab Help. Accessed April 23, 2020. Scilab-Link

“Scilab Programming – WHILE Loops – x-Engineer.Org.” Accessed April


13, 2020. x-Engineer-Link

“Scilab Programming – SELECT CASE Conditional Statements – x-


Engineer.Org.” Accessed April 16, 2020. x-Engineer-Link

“Scilab Programming – IF ELSE Conditional Statements – x-Engineer.Org.”


Accessed April 17, 2020. x-Engineer-Link

SHASHIKANT. ‘Editing Vectors and Matrices in Scilab – x-Engineer.Org’.


Web page. Accessed 26 March 2020.. x-Engineer-Link

Stack Overflow. “How Does Subplot Work and What Is the Difference
between Subplot(121) and Subplot(1,2,1) in MATLAB?” Accessed April 26,
2020. Stack Overflow Link

“State-Space Representation.” In Wikipedia, February 21, 2020. Wikipedia-


Link.

Stroud, K. A., and Dexter J. Booth. Engineering Mathematics. 5 edition. New


York: Industrial Press, Inc., 2001. Amazon Link

“The Fastest Way to Define a Function in Scilab – x-Engineer.Org.”


Accessed April 29, 2020. x-Engineer-Link

Toochinda, Varodom. “Feedback Control with Scilab and Arduino.” Blog.


Feedback Control with Scilab and Arduino, September 2016. Link

Verma, Rachna, and Verma, Arvind. “Introduction to Scilab EBook.”


Accessed May 19, 2020. Amazon-Link

“What Is the Intuition of Eigenvector and Eigenvalue from a Control System


Perspective?” ResearchGate. Accessed May 21, 2020. ResearchGate-Link

Yaqub, Tahir. An Introduction to Xcos: [A Free Alternative to MATLAB


Simulink]. Accessed May 18, 2020. YouTube-Link

Yaqub, Tahir. Making Your First Simulation in Scilab Xcos [Unit Step
Response]. Accessed May 21, 2020. YouTube-Link
Index
2
2D Plotting 1

A
Acknowledgment 1
App. Development Tasks in Detail 1
Apple Mac 1
Application Development 1
Ask user to choose option 1
Assigning Variable 1

B
Break in a for-end loop 1
Built-in Constants 1

C
Common Built-in Functions 1
companion website 1
Custom Functions 1

D
Defining online custom function 1
Determinant of Matrix 1
Display Data Using mprintf() 1

E
Eigenvalues and Eigenvectors 1
Elementary Operators 1
Error Handling 1
error-handling routines 1

F
For Loops 1
For Loops - Nested 1

I
If Else Conditional Statements 1
Identity Matrix & Inverse of Matrix 1
Importing Data 1
Inputs to Scilab could be in two ways 1
INRIA 1
install Scilab 1

L
Linux 1
List of Figures 1
Logical Operators 1

M
MATLAB 1
Matrices – Addition & Subtraction 1
Matrices – Multiplication 1
Matrix Operation Using Scilab 1
matrix when multiplied by an identity matrix 1
mprintf-Console Output in a table-format 1
MS Windows 10 installation 1

P
plot2d 1
plot 1

R
Read csv-file as a matrix 1
Rule of matrix multiplication 1

S
Scilab as a Simple Calculator 1
Scilab Environment 1
Scilab Installation 1
Scilab Variable List 1
SciNotes - Storage of Programs in Scilab 1
Select Case Conditional Statements 1
Select Case to do the plotting 1
Series Content 1
Series Introduction 1
Silab 1
Solve Linear Equations by Matrices 1

T
Table of Contents 1
Transpose of Matrix 1
type 1
typeof 1

U
user-defined function 1
user-input 1
user-input errors 1
user-input-validation 1

W
While Loop 1
Who This Book Is Intended For 1
X
X = A-1 .B 1
XCOS 1
XCOS Simulations 1
IX IX Other Books by Author

Bridge Resource Management: Teamwork and Leadership


Paperback – December 20, 2013
by Kalyan Chatterjea (Author), Captain Alex G. Labor (Author),
Captain Francisco J. Vidal (Author)
Amazon-Link
DESCRIPTION
This publication on Bridge Resource Management - Teamwork
and Leadership (BRM-TL) covers the non-technical skill
requirements of a bridge-team as specified in the IMO s STCW
Tables A-II/1 and A-II/2 for both operational and management
levels (including 2010 Manila Amendments). The book is meant
to support a simulator-based course covering these requirements.
On completion of the BRM-TL course, as detailed in this book,
participants are expected to gain enhanced knowledge in the
areas of effective management and optimum utilisation of all
resources, required for the safe and successful conduct of a ship's
voyage. BRM-TL course emphasises the non-technical skills of
the bridge-team, which include managing human factors,
effective communications, processes of team-building and
leadership . To manage bridge processes, the book provides
guidance on situational awareness, including team situational
awareness, decision-making, contingency planning, as well as
task management covering fatigue and workload planning.
Additionally, this book introduces the concept of behavioural
markers for assessing these soft skills to establish performance
levels during a simulated exercise. Examples of behavioural
markers applicable in a full-mission simulator-based exercise are
also included.

KEY FEATURES
Detailed coverage of non-technical skills required by the IMO s
STCW Tables A-II/1 and A-II/2 for both operational and
management levels (including 2010 Manila Amendments)
Coverage of specific knowledge in the areas of: - effective
management and optimisation of bridge resources required for
the successful conduct of a ship s voyage - management of
human factors - effective communications - processes of team-
building & leadership - guidance of situational awareness
including team situational awareness - decision-making -
contingency planning - task management including fatigue &
workload planning Introduces the concept of behavioural
markers for assessing soft skills to establish performance levels
during a simulation exercise. This book can be used as a
guidebook in a bridge resource management course run on a full-
mission bridge simulator.

TABLE OF CONTENTS
Tables of Figures
Authors
Preface
Introduction
Chapter 1 Human Factors
Chapter 2 Communications
Chapter 3 Teamwork and Leadership
Chapter 4 Managing Bridge Processes
Chapter 5 Assessing Performance Behavioural Markers
Appendix
Index
X About the Author

Kalyan Chatterjea started his career as a sea-going engineer and sailed


for eleven years rising to the rank of Chief Engineer. After years of
active involvement in the maritime industry, he taught at the Singapore
Maritime Academy (SMA) for nearly twenty years teaching various
maritime subjects on engine, as well as deck side, after which he worked
two years at the Malaysian Maritime Academy in Malaysia as Head of
Research. He came back from Malaysia and worked for five years as an
academic consultant at EMAS Training Academy and Simulation
Centre, Singapore, teaching and developing courses for the offshore
industry. His final teaching post was at the Wavelink Maritime Institute,
Singapore, where he was the Head, Engineering Section for almost five
years. He has an Extra First Class Certificate (Motor & Steam) from
South Tyneside College, UK. He also holds an MSc in Systems,
Controls, and Information Technology from the University of Sheffield,
UK. Additionally, He holds a Master of Education from the University
of Sheffield, UK. His main interest is in improving the teaching and
learning of marine technology through infotech.
Table of Content
I. Title Page
II. Series Contents
III. Series Introduction
IV. Acknowledgment
V. Table of Contents
VI. List of Figures

1. Scilab Basics - Introduction


2. Who This Book is Intended For
3. Scilab Installation
4. Scilab Environment
5. Scilab as a Simple Calculator
6. Matrix Operation Using Scilab
7. Matrices – Addition & Subtraction
8 Matrices – Multiplication
9. Identity Matrix & Inverse of Matrix
10. Solve Linear Equations by Matrices
11. Transpose of Matrix
12. Determinant of Matrix
13. Eigenvalues and Eigenvectors
14. SciNotes - Storage of Programs in Scilab
15. Display Data Using mprintf()
16. If Else Conditional Statements
17. For Loops
18. While Loops
19. Select Case Conditional Statements
20. Custom Functions
21. Importing Data
22. 2D Plotting
23. Application Development
24. XCOS Simulations

VII. Bibliography
VIII Index
IX Other Books by Author
X About the Author

You might also like