0% found this document useful (0 votes)
1 views40 pages

Nav Roop Kaur Sci Lab

The document provides an introduction to Scilab, a scientific software package for numerical computations, detailing its features, toolboxes, and basic operations. It includes various experiments demonstrating the use of Scilab for programming tasks such as matrix manipulations, control statements, and special matrices. Additionally, it explains how to access help commands and the functionalities of different operators within Scilab.

Uploaded by

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

Nav Roop Kaur Sci Lab

The document provides an introduction to Scilab, a scientific software package for numerical computations, detailing its features, toolboxes, and basic operations. It includes various experiments demonstrating the use of Scilab for programming tasks such as matrix manipulations, control statements, and special matrices. Additionally, it explains how to access help commands and the functionalities of different operators within Scilab.

Uploaded by

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

INDEX

[Link]. Title Date Page Sign. Of


No. the
teacher
• Introduction to Sci Labs
• Use of help command to get help about
different in - built functions in Scilab.

• Write a program to show the output of


various unary and binary operators

• Write a program for Matrix Manipulations


(reshaping matrices, expanding matrix size,
appending or deleting a row/column to a
matrix and concatenation of matrices)

• Write a program to demonstrate the use of


special matrices.

• Write program to show output of various


matrix and array operations

• Write a program to demonstrate the use of


various control statements

• Write a program to print factorial of a


number using Scilab

• Write a program using functions and plot


results
Introduction to Scilab
Scilab is a scientific software package for numerical computations providing a powerful open
computing environment for engineering and scientific applications. It was developed since
1990 by researchers from INRIA (French National Institute for Research in Computer
Science and Control) and ENPC (National School of Bridges and Roads). It is now
maintained and developed by Scilab Consortium since its creation in May 2003 to broaden
contributions and promote Scilab as worldwide reference software in academia and industry.
In July 2008, the Scilab consortium integrated into Digiteo Foundation.

Since 1994 it is distributed freely along with source code through the Internet and is currently
being used in educational and industrial environments around the world. Scilab includes
hundreds of mathematical functions with the possibility to add interactively functions from
various languages (C, Fortran etc.). It has sophisticated data structures (including lists,
polynomials, rational functions, linear systems...), an interpreter and a high-level
programming language. Scilab has been designed to be an open system where the user can
define new data types and operations on these data types by using overloading.

A number of toolboxes are available with the system:

• 2-D and 3-D graphics, animation

• Linear algebra, sparse matrices

• Polynomials and rational functions

• Scicos: a hybrid dynamic systems modeler and simulator

• Differentiable and non-differentiable optimization

• Signal processing

• Metanet: graphs and networks

• Statistics

• And a large number of contributions for various domains.

To access Scilab on Cloud


Scilab on Cloud facilitates execution of the codes for particular example(s) online. The
results can then be verified with the solved example(s) from the textbook. It is also possible
to change the values of the variables and in fact, the code itself, and execute it. In addition to
the given examples, one can also copy and paste (or) write a new code in the input box
provided and execute the same.

The FOSSEE team has created a submission portal that allows the code for each example to
be uploaded individually. From the view point of convenience, web based Scilab engine has
been created by FOSSEE. For enhanced performance and safety, this facility has been ported
by the FOSSEE team to the Garuda Grid/ NVLI Grid.

Special Features of Scilab:

• Interactive GUI consists of three modules: Data management, modelling and


optimization
• Interface with other languages like C, C++, Fortran, python, .net and java
• Scilab is available in the following computing engines like C, C++, Java, API and
Python
• Integrating with third party software’s like lab view, excel, insight, mode frontier and
alter nova
• MATLAB to SCI LAB conversion using “mfile2sci” function
• Scilab supports advanced functionalities such as X2C and SWIG [Simplified Wrapper
Interface Generator].

Basic Elements of Scilab:

• Booleans
• Integers
• Complex numbers
• Floating point integers
• Elementary and mathematical functions
• Comments [//] and continuous lines [……….]
• Pre-defined mathematical variables like atan, coth, cosh, sinh etc.
• Variable names: Ascii letters starts from “‘a’ – ‘z’” to “‘A’- “Z’” and digits from ‘0’ to
‘9’

Scilab Operations:

• Matrix Operation
• Vector Operation
• Functions
• Plotting
• Simulation
• Looping and Branching

Associated file types:

• . HYPERLINK "[Link] HYPERLINK


"[Link] HYPERLINK
"[Link] Scilab Script
• . HYPERLINK "[Link] HYPERLINK
"[Link] HYPERLINK
"[Link] Scilab Macro Definitions
• . HYPERLINK "[Link] HYPERLINK
"[Link] HYPERLINK
"[Link] Scilab XML Diagram
• . HYPERLINK "[Link] HYPERLINK
"[Link] HYPERLINK
"[Link] Scilab ASCII Diagram
• . HYPERLINK "[Link] HYPERLINK
"[Link] HYPERLINK
"[Link] Scilab Binary Diagram

Experiment-1
Use of help command to get help about different in-built
functions in Scilab.
1. Start up Scilab

2. See a window of Scilab.

3. Enter Scilab commands at the prompt (-->).

4. Click on the “Help” menu opens up the Help Browser, showing a list of topics on
which help is available.

5. Clicking on the relevant topic takes you to Hyperlinked documents similar to web
pages.
6. The Help Browser has two tabs – Table of Contents and Search.

7. Table of Contents contains an alphabetically arranged list of topics. To see the list of
functions available in Scilab, search for Elementary Functions in the contents page of
Help Browser. Other useful functions may be available under different headings.

8. Use the Search tab to search the help for string patterns. Help on specific commands
can also be accessed directly from the command line instead of having to navigate
through a series of links. Thus, to get help on the Scilab command “help”, simply type the
following command at the prompt.

9. The help browser offers two views of the help content contents view and search view.

10. In the contents view, topics are listed in a tree structure which can be expanded or
collapsed to browse through the help content. Alternately, the search view allows the user
to type in search patterns and topics matching the pattern are listed.
Getting help: In the Help menu there are three options that you can use to get help from
SCILAB:

• Help Dialogue: This provides a list of help items classified by chapters. There will be
two windows available using this option, the lower window shows the chapter titles while
the upper window shows the subjects in the chapter currently selected. Select the item
you want to display and press the Show button located to the left side of the help window.

• Topic: Enter a topic you want help with in the window shown when using this option
and press the OK button. If no help is available you will get a message indicating NO in
the main SCILAB window. If help is available, SCILAB will show you the corresponding
instructions. For example, use this option and request information on the keyword ‘inv’; it
will give you information on the inverse operation for matrices.

• Appropriate: Enter a keyword related to the topic that you are looking for (e.g.,
inverse) and press the OK button. You will see a window with topics including the
keyword you selected. Scroll through the list and find that topic closer to your interest
(e.g., inv - matrix inverse), and press OK to get information on that particular topic.
Use as:

To access the online help,

• Click on Scilab Help in the menu bar, or

• Type in the console: -->help

To get help with any function, type help in the console followed by the name of the
appropriate function.

For example: -->help sin displays help for sin (sine) function.
Experiment-2
Write a program to show the output of various unary and
binary operators
What is an Operator?
• Operator is a symbol or special character which is used to perform a specific task, the
task/meaning of operator is defined in the compiler. For example, + is an operator
which is used to add two values.

What are Unary Operators?


• The Operators which operate on Single Operand known as Unary Operators, some of
the unary operators are:
++ Increment Operator
-- Decrement Operator
& Address of Operator
- Unary Minus Operators
~ (One’s Compliment) Negation Operator
! Logical NOT
What are Binary Operators?
• The Operators which operate on Two Operands are known as Binary Operators, some
of the binary operators are:
+ Binary Plus Operator
- Binary Minus Operator
== Equal to Operator
< Less than Operator
Experiment-3
Write a program for Matrix Manipulations (reshaping
matrices, expanding matrix size, appending or deleting a
row/column to a matrix and concatenation of matrices)
• Reshaping of Matrix:

Reshaping of a matrix in Scilab can be done using the tools shown in the figure below:

1. Reshaping of a matrix means changing the shape of a matrix.

2. Changing shape of matrix means changing dimensions of matrix, i.e., for example
changing a 2x3 matrix to a 3x2 matrix.

3. The dimensions of matrix can be changed using transpose, as shown in figure above.

4. First the elements of “matrix A” are entered, and then the transpose of matrix A is
calculated. The transpose is represented as A’.

5. The Resultant matrix is represented in a single line using A (1) as shown above.
• Expanding matrix size:

Syntax:

Resizematrix

resMat = resize_matrix(mat, nbRows, nbCols)


resMat = resize_matrix(mat, nbRows, nbCols, resType)
resMat = resize_matrix(mat, nbRows, nbCols, resType, padding)
resMat = resize_matrix(mat, nbRows, nbCols, "", padding)

resMat = resize_matrix(mat, newSizes)


resMat = resize_matrix(mat, newSizes, resType)
resMat = resize_matrix(mat, newSizes, resType, padding)
resMat = resize_matrix(mat, newSizes," , padding)

• mat:
Input matrix or hyper matrix. Booleans, encoded integers, decimal-encoded numbers
(real or complex), polynomials, or text is supported.

• nbRows:
New number of rows of the resized matrix. Exceeding rows are trimmed. Missing
rows are added by padding. Setting nbRows < 0 keeps the current number of rows.

• nbCols:
New number of columns of the resized matrix. Exceeding columns are trimmed.
Missing columns are added by padding. Setting nbCols < 0 keeps the current number
of columns.

• newSizes:
Vector specifying the new sizes along each dimension of mat. To keep a new size
equal to the current one, just set it to -1.

• padding:
Optional scalar of same type as mat, specifying the content to set in elements created
when the size along a dimension is increased. The default padding is done with 0 or ""
(text), or %f (Booleans).

• resType:
Optional text word specifying the data type into which the resized matrix must be
converted. "boolean", "constant", "string", "int8", "uint8", "int16", "uint16", "int32",
"uint32", "int64", and "uint64" are supported.
• resMat:
Resized (and converted) matrix or hyper matrix

• Concatenation of a matrix: To concatenate several arrays “cat” function is used.


Syntax:
y = cat (dim, A1, A2... An)
Description:
y=cat(dims,A1,A2,...,An): y is the result of the concatenation of the input
arguments A1,A2,...,An.
If dims=1, then the concatenation is done according to the rows
A1=[1 2 3; 4 5 6]; A2=[7 8 9; 10 11 12]; y=cat(1,A1,A2) => y=[1 2 3; 4 5 6 ;7 8 9; 10 11 12].

Experiment-4
Write a program to demonstrate the use of special
matrices.

Like MATLAB, Scilab has a number of functions that create “standard” matrices or matrices
of random numbers. Many of them have the same or very similar names. The arguments or
the output may be slightly different.

Scilab Description
[] Empty matrix
Diag Create diagonal matrix or extract diagonal from matrix
Eye Identity matrix (or its generalization)
Ones Matrix of ones
Rand Matrix of random numbers with uniform or normal
distribution
Zeros Matrix of zeros

The empty matrix [] in Scilab behaves slightly different than the corresponding [] in Matlab;
in Scilab, for example,

-->a = [] +3

a = 3.

Whereas in Matlab

>>a = [] +3

a = [].
The standard syntax with two arguments to define dimensions works for functions zeros, ones
& rand; the same way it does for Matlab.

Use of Rand Function:

Use of Ones and Zeros:


Experiment-5
Write programs to show output for various matrix and
array operations
Scilab is like a heaven for Linear Algebra related problems, as it recognizes matrices and
their operations.

Defining a matrix is easy and simple. There are a lot of in-built functions to perform various
tasks like transposing a matrix, multiplying or adding matrices and more.

Matrix Operations
• Defining a Vector (Using Spaces)

• Defining a Vector (Using Commas)

• Length of a Vector

• Vectors Using Various Operations

• Transpose of a Vector

• Matrix Representation

• Size of a Matrix

• Transpose of Matrix
The following are some of the examples of various Matrix Operations performed in Scilab.

• Matrix operations

Output
For Multiplication and Addition of matrices A & B
Output
For Transpose and determinant of the matrices A & B
Experiment-6
Write a program to demonstrate the use of various control
statement
There is control flow of Scilab control structures as given below with control statements &
their descriptions.
Control flow
• abort — interrupt evaluation.
• break — keyword to interrupt loops
• case — keyword used in statement "select"
• continue — keyword to pass control to the next iteration of a loop
• do — language keyword for loops
• else — keyword in if-then-else and select-case-then-else
• elseif — keyword in if-then-else
• end — end keyword
• for — language keyword for loops
• halt — stop execution
• if — keyword for conditional execution
• pause — pause mode, invoke keyboard
• resume — return or resume execution and copy some local variables
• return — return or resume execution and copy some local variables
• select — select keyword
• then — keyword in control flows 'if' and 'select'
• catch — beginning of catch block in try-catch control instruction
• while — while keyword

• if
Keyword for conditional execution
Syntax
if expr1 then
statements
elseif expi then
statements
....
else
statements
end
Description: The if statement evaluates a logical expression and executes a group of
statements when the expression is true.

• else
Keyword in if-then-else and select-case-then-else
Description: Used with if and select

• elseif
Keyword in if-then-else
Description: If there is more than one condition then keyword else if is useful. If there is
more than one elseif then the first true condition is selected (even other also are true).

• end
End keyword
Description: Used at end of loops or conditionals. for, while, if, select must be terminated
by end.
• then
Keyword in control flows 'if' and 'select'
Description: Used in control flows if and select. Each then keyword must be on the same
line as its corresponding if, elseif or case [Link] keyword then can be replaced by a
carriage return or a comma.
The expri are expressions with numeric or Boolean values. If expri is a non-scalar value then
the condition is true only if all entries of this value are true or different from zero.

The optional elseif and else provide for the execution of alternate groups of statements.
An end keyword, which matches the if, terminates the last group of statements. The line
structure of if is not significant, the only constraint is that each then keyword must be on the
same line as its corresponding if or elseif keyword.

• for
Language keyword for loops
Description: Used to define loops. Its syntax is: for variable=expression, instruction,..,
instruction,end.
for variable=expression do instruction, instruction, end
If expression is a matrix or a row vector, variable takes as values the values of each column
of the matrix.
A particular case uses the colon operator to create regularly spaced row vectors, and is similar
to traditional for loop forms: for variable=n1:step:n2, ...,end
If expression is a list variable takes as values the successive entries of the list.
• while:
while keyword
Description:The while clause must be terminated by "end".
while expr,instructions,..., end
while expr do instructions..., end
while expr then instructions..., end
• Select
select keyword
Syntax:
select variable
case value1 then
instructions 1
case value2 then
instructions 2
...
case valuen then
instructions n
[else instructions]
end
Experiment-7
Write a program to print factorial of a number using
Scilab
Syntax
f = HYPERLINK "[Link]
HYPERLINK "[Link] HYPERLINK
"[Link] ( HYPERLINK
"[Link] HYPERLINK
"[Link] HYPERLINK
"[Link]
Description
f = factorial (n) returns the product of all positive integers less than or equal to n, where n is a
non-negative integer value. If n is an array, then f contains the factorial of each value of n.
The data type and size of f is the same as that of n.
The factorial of n is commonly written in math notation using the exclamation point character
as n!
Experiment-8
Program to plot 2D and 3D Plots
The graphics window
Opening a graphics window:

A graphics window opens automatically when making any plot. It is possible to plot curves, surfaces,
sequences of points.

To obtain an example of curve in Scilab on cloud, type:

-->plot

2-D and 3-D plots


Plot command is used to create plots in the plane. Color and appearance can be specified by putting
indications of color and points style within quotes:

 Colors

"b" = blue (by default), "k" = black, "r" = red, "g" = green, "c" = cyan, "m" = magenta, "y" = yellow,
"w" = white

Basic plots / Plots in 2 Dimensions


 To plot a point

Plot the point A (1 ; 2) with a red point

 To plot a segment
Plot the segment [AB] in blue (by default) with A (1 ; 2) and B (3 ; 5).
 Plots of plane curves defined by functions y=f(x)
For a function x→ f(x) the values of x are specified using the linspace command by writing:
x=linspace (a,b,n); in which a is the smallest value of the variable x, b the highest value of x, and n
the number of values calculated between a and b.

Do not forget the “; “symbol otherwise all n values of x will be displayed.

Consider two functions f and g defined over the interval [-2 ; 5] by:

f(x) = (x² + 2x)e-x , and g(x) = sin(x/2)

We plot the curve defined by f, in blue by default:


By adding the f(x) & g(x), we obtain the plot of two curves, that of ‘f’ in red and that of ‘g’ in green.
 Plots of sequences of points

The most common case is to plot the sequences of points M (n, u (n )) after calculating the
coordinates u(n) of a vector u. Plot(u,"*r") specifies the style and color of the points in quotes: red
and non-connected stars.
 Bivariate statistical data

Bivariate statistical data are given in the form of two vectors: X and Y.

Plot (X, Y,"<") will plot a scatter plot of M (Xi;Yi ) with blue triangles.
Plots in 3 Dimensions
Scilab can be used to plot surfaces and curves in space, with many options for the treatment of
hidden faces, face colors, points of view, etc. The following examples will illustrate 3-D plots.

The surf function can be used for plotting surfaces. This function has three input variables, x, y and z.

 x and y are respectively vectors of size m and n corresponding to points on the axes (0x )
and (0y ).
 z is a matrix of dimension n ×m with element zij corresponding to the height of the point
with X-coordinate xi and Y-coordinate yj.

To plot the surface defined by a function of the form z = f(x, y), it is necessary to:

• Define function f

• Calculate z=feval (x, y, f)'

 feval (x, y, f) returns the m×n matrix whose ij element is f(Xi , Yj) which will be transposed
by using the single quote symbol “ ' “

• Execute surf(x,y,z).

To plot the surface z = 2x² + y² (elliptic paraboloid):


Curves in space may be plotted using the param3d function.

param3d has three arguments, x, y and z, each vectors has the same dimension and corresponds to
the points (xi , yi , zi) on the curve.

To plot the helix defined by (x = cos (t), y = sin (t), z = t ):

You might also like