scilab programming - the open source platform for...
TRANSCRIPT
Scilab ProgrammingThe open source platform for numerical computation
Satish Annigeri Ph.D.
Professor, Civil Engineering DepartmentB.V.B. College of Engineering & Technology
Hubli 580 [email protected]
27 Sep, 2010
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 1 / 38
Introduction
About Scilab
Scilab is an open source numerical computation platform
Multiplatform - Windows, Linux, Mac OS X, Solaris, Unixes
An interactive numerical toolMatrices are a built-in data type in ScilabAll operations on matrices are built-in
Has a scripting programming language to write functions and developlibraries
Has 2D and 3D graph plotting capabilities
Has a large number of libraries contributed by the communityImage Processing, Optimization, Genetic Algorithms, Neural NetworksLabView Gateway - connects NI LabView with Scilab and accessScilab’s power within LabViewXcos - hybrid dynamic systems modeller and simulator
Interfaces with code written in Fortran, C, C++
Embeddable - Scilab/Xcos C code generator for FLEX board
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 2 / 38
Introduction
Current Status of Scilab
Current version is 5.3.0 beta 3
Scicos is now called Xcos
New improved code editor
Dockable application windows - Editor, Graphics window
New architecture for modular plug-ins - ATOMS
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 3 / 38
Introduction
Scilab Applications
Civil Engineering
Matrix structural analysis, Finite element analysisXcos - Mechanical vibration, Hydraulic circuit analysis
Electrical Sciences
Xcos - Circuit simulationFilter designImage processingControl systemsHardware interfacing, Sensors, Embedded systems
Mechanical Sciences
RoboticsFinite element analysis
Computer Science
Graph theoryImage processingANN, GA, Fuzzy logic
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 4 / 38
Introduction
Agenda
Scilab Programming Language
Data types, Operators, Expressions, StatementsScript filesFunctions, Input and output arguments, Variable number of arguments
File Operations
Opening and closing filesReading from filesWriting to filesReading Microsoft Excel filesWriting CSV text files
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 5 / 38
Introduction
Scilab Resources
Scilab Website
Scilab website - http://www.scilab.orgXcos website - http://www.scilab.org/products/xcosScilab documentation - http://www.scilab.org/support/documentationExtending Scilab -http://www.scilab.org/communities/developer zone/extensionsTools for Scilab development -http://www.scilab.org/communities/developer zone/tools
Scilab Tutorials
Tutorial on Scilab website -http://www.scilab.org/support/documentation/tutorialsMy Lulu webpage has two tutorials
Introduction to Scilab - http://bit.ly/bB5GHLMatrix Structural Analysis of Plane Frames - http://bit.ly/cXjoG4
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 6 / 38
Introduction
Preliminaries
Scilab can be used in interactive mode like a calculator
Scilab can be used in batch mode to execute a set of commandswritten in a file, called a script file.
Scilab can be used to write functions like any other programminglanguage
Global local variablesArgument passing mechanismScilab is weakly typed - No stringent restrictions on type declaration,type conversion
Scilab is case sensitiveOutput of a command is immediately echoed on the consoleMultiple commands on the same line can be separated by a comma (,)or a semicolon (;)A semicolon (;) at the end of a statement suppresses echoing ofoutput from the statementSingle line comments begin with // and last up to the end of the line
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 7 / 38
Introduction
Scilab Environment
Scilab command prompt is: -->
Access to on-line helpType -->help
Press F1
From the menu choose ? =¿ Scilab Help
On-line help offers two choicesTable of contentsSearch for specific patterns
Direct access to help on Scilab functions: -->help pattern
Scilab constantsπ: %pi
ε: %eps
NaN: %nane: %e
i =√−1: %i
inf: %inf
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 8 / 38
Introduction
Scilab Variables
Variable names follow the same convention as in C
Names can contain alphanumeric charactersNames must begin with an alphabetAn underscore character is treated as an alphabet
Variables can be assigned values
Name of a variable in an expression evaluates to its value
Value may be a real number, imaginary number, matrix, string or anyother Scilab data type
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 9 / 38
Introduction
Scilab Workspace
Examine the Scilab workspace
List names of contents of workspace: -->who
Detailed list of contents of workspace: -->whos
List names of constants: -->whos -type constant
List names of contents beginning with ”a”: -->whos -name a
Objects can be of the following data types
ConstantStringBooleanFunctionLibraryPolynomialRationalCell (ce)ListStruct (st)
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 10 / 38
Introduction
Scilab Workspace
Save entire contents of the workspace to a disk file
Save selected variables from the workspace to a disk file
Clear entire contents of the workspace
Clear selected variables from the workspace
Load data from a previously save workspace
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 11 / 38
Introduction
Matrix Operations in Scilab
Defining matrices
Matrices are enclosed between square bracketsElements are defined row by row. All rows must contain the samenumber of columnsElements in a row can be separated by a comma or a spaceRows are separated by a semi colon or by a carriage returnSemi colon at the end of the last row is optional
Simple matrix operations on two matrices a and b
Addition c = a + b
Subtraction c = a - b
Multiplication c = a * b
Right division c = a / b Same as c = a ∗ b−1 or c = ab
Left division c = a b Same as c = a−1 ∗ b or c = ba
Transpose b = a’
Power b = a∧2 or b = a**2
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 12 / 38
Introduction
Automating Scilab
Initially you may be contented using Scilab as a powerful interactivecalculator
matrix computationsgraphicsrich set of built-in functions
You will soon begin to yearn for more
Can I store repeated commands and execute them all at once?
Can I modularize repeated tasks and call them when I need?
Answer to both the questions is: Yes
We will take this up in three steps:
We will take a look at the Scilab Programming LanguageWe will learn how to write Scilab functionsWe will learn how to write Scilab script files
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 13 / 38
Scilab Data Types
Scilab Programming Language
Scilab has a programming language of its own
Every command that can be typed at the Scilab command prompt(without generating an error of course!) is a valid statement in Scilabprogramming language.
Your knowledge of using Scilab interactively becomes the startingpoint for programming
Offers features expected from a traditional procedural languages:
Data types: Built-in and User-definedControl structures: if then else if, for, do, selectFunctions: input arguments, output arguments, input and outputarguments
Does not currently support object oriented programming
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 14 / 38
Scilab Data Types
Scilab Data Types
Let us try our hand with a few Scilab data types
Constant-->a = rand(3,3)*10;
-->typeof(a)
constant
Boolean-->b = a < 5;
-->typeof(b)
boolean
Function -->whos
-->typeof(whos)
function
String -->s = ’Satish’;
-->typeof(s)
string
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 15 / 38
Scilab Data Types
Scilab Data Types...
Polynomial-->p1 = poly([2 3 5], ’x’];
# polynomial in ’x’ with three roots 2 3 and 5
-->typeof(p1)
polynomial
Rational-->p2 = poly([1 4], ’x’);
-->p3 = p1 / p2;
-->typeof(p3)
rational
Structure-->x.name = ’Satish’;
-->x.salary = 20e3;
-->typeof(x)
st
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 16 / 38
Scilab Data Types
Scilab Data Types...
Other data types available in Scilab are:
Handle
List
State-Space
Sparse - for sparse matrices
Boolan Sparse - for boolean sparse matrices
Hypermat - N dimension array with N ¿= 3
Cell - Cell array
fptr - Scilab intrinsic (C or Fortran code)
Pointer
Size Implicit
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 17 / 38
Operators
Operators
[ ] Matrix definition( ) Extraction, eg. m = a(k)’ Transpose− Subtraction\ Left division∧ Exponent.\ Elementwise left division.∧ Elementwise exponent; Statement separator( ) Insertion, eg. a(k) = m+ Addition* Multiplication/ Right division.* Elementwise multiplication./ Elementwise right division
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 18 / 38
Control Structures
Control Structures
Loop Constructs
for - Repeat a block of statements based on an index variable
while - Conditional repetition of a block of statements
Select Constructs
if then, if then else, if then elseif else
select - similar to switch in C
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 19 / 38
Control Structures
for Loop
In its simplest form, let us use a for loop to print a sequence of numbers
Numbers 1 to 5-->for i = 1:5
-->disp(i)
-->end
1.
2.
3.
4.
5.
Odd numbers between 1 and 5-->for i = 1:2:5, disp(i), end
1.
3.
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 20 / 38
Control Structures
for Loop
Even numbers between 1 and 5-->for i = 2:2:6, disp(i), end
2.
4.
With fractional increment-->for dx = 0:%pi/16:%pi, disp(dx), end
0.
0.1963495
...
3.1415927
In reverse gear, if you so wish-->for dx = 10:-2:5, disp(dx), end
10.
8.
6.
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 21 / 38
Control Structures
for Loop
Every for loop must close with a corresponding end, no matter whatthe depth of nesting is
Another accepted form of the for loop is with the keyword do
for variable = expression do
statement
end
If expression is a matrix or a row vector, then variable takes asvalues the values of each column of the matrix or row vector
If expression is a list variable, then variable takes as values thesuccessive entries of the list
for loop can be interrupted with the break statement, forcing theend of the innermost for loop
One cycle of for loop can be skipped with the continue keyword
Other means of interfering with the for loop are:pause, return and abort
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 22 / 38
Control Structures
if then, if then else
General format of if in different combinations is
Only one test-->a = -2;
-->if a < 0 then
--> disp(’Negative’)
-->end
Negative
One test with an alternativea = 2
-->if a < 0 then
--> disp(’Negative’)
-->else
-->disp(’Non-negative’)
-->end
Non-negative
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 23 / 38
Control Structures
if then elseif else
Multiple test with an alternativea = -2
-->if a < 0 then
--> disp(’Negative’)
Negative
-->elseif a == 0 then
-->disp(’Zero’)
else
-->disp(’Positive’)
-->end
Notice that the word Negative is displayed even before you completethe if block. This is because of short-circuiting of boolean expressionevaluation. If this alternative is true, then others need not beevaluated.
Try this loop with different values of a
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 24 / 38
Control Structures
select
select is useful when the number of tests in a if block is large. Butcan handle only ”equal to” comparisons and not inequalities. It issimilar to the switch block in C.-->ch = input(’Enter an integer: ’);
3
-->select ch
-->case 1 then
-->disp(’One’)
-->case 2 then
-->disp(’Two’)
-->case 3 then
-->disp(’Three’)
Three
-->else
-->disp(’Dah!’)
-->endSatish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 25 / 38
Control Structures
Script Files
Script files are text files containing Scilab statements
There is no separate workspace for the script file
The statements take their input from the Scilab workspaceOutput generated by the statements are stored in the Scilab workspace
Useful for testing and debugging statements
Useful to write the main program (similar to the main() function inC programming language)
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 26 / 38
Scilab Functions
Scilab Functions
Functions help modularize code
They define a well defined interface to the function and serve as ameans of communication between the designer of the function andthe consumer of the functionFunction interface consists of
Name of the function - usually indicates the purpose of the function.Purpose is further explained in the documentationInput arguments - variables sent into the function from the callingmodule. Appear on the RHS of assignment statements.Output arguments - variables whose values are calculated inside thefunction and sent out to the calling module. Appear on the LHS ofassignment statements.
Calling a function invokes the function. Variables in the function callare called input and output parameters.
Number and type of arguments (as in the function definition) andparameters (as in the function call) must match.
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 27 / 38
Scilab Functions
Scilab Function Skeleton
function [out1, out2, ...] = function-name(in1, in2, ...)
statement-1;
statement-2;
...
statement-n;
endfunction
Function definition begins with the keyword function
A function can have one or more output argumentsFunction name must be chosen to reflect its purpose
Function name can consist of alphanumeric charactersFirst character must be an alphabetUnderscore is treated as an alphabet
A function can have zero or more input arguments
Function definition ends with the keyword endfunction
A comment is begun by a pair of forward slashes (//) and lastsuntil the end of line
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 28 / 38
Scilab Functions
Function to Calculate Length of a Line
Consider two points on a plane P1(x1, y1) and P2(x2, y2)
The length between the two points is L =√
(x2 − x1)2 + (y2 − y1)2
Let us write a simple function to obtain the length and make a fewimprovements to increase its usefulness.
Scilab has a built-in code editor named SciPad
Syntax color highlightingEdit and save codeAll features of a code editor - search, search and replace, save as etc.Compile source code and load into Scilab workspace
function [L] = Len(x1, y1, x2, y2)
// Returns length of line between (x1,y1) and (x2,y2)
dx = x2 - x1;
dy = y2 - y1;
L = sqrt(dx∧2 + dy∧2);endfunction
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 29 / 38
Scilab Functions
Use the Scilab Function
Save the function into a file in a known folder. Note down thefolder location and filename for later use.
In SciPad, click on Execute ⇒ Load into Scilab
Switch to Scilab and confirm the function is loaded into the workspace-->whos -type function
Name Type Size Bytes
....
Len function 664
Call the function with known input and test the output-->Len(0, 0, 4, 3)
ans =
5.
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 30 / 38
Scilab Functions
Test the Function
Give input in different ways and test-->x1=0; y1=0; x2=4; y2=3;
-->Len(x1, y1, x2, y2)
ans =
5.
Identify its shortcomings
Does not adapt itself to points in 3D space P1(x1, y1, z1) andP2(x2, y2, z2). L =
√(x2 − x1)2 + (y2 − y1)2 + (z2 − z1)2
Improve the function
Instead of giving coordinates (x1, y1, z1) and (x2, y2, z2) as input, givevectors with coordinates p1 and p2 as input. Point p1 can be (x1, y1)or (x1, y1, z1) depending on whether you want it to be a point in aplane or in space.Make the function work for points in a plane as well as in space
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 31 / 38
Scilab Functions
Test Improved Function
function [L] = Len(p1, p2)
dx = p2 - p1; // works for points in 2D as well as 3D
L = sqrt(sum(dx.∧2))endfunction
This time around, input consists of two points, each point having twocoordinates arrnged as two elements in a vector-->Len([0, 0], [4, 3])
ans =
5.
Try a point in space-->Len([0, 0, 0], [4, 3, 0])
ans =
5.
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 32 / 38
Scilab Functions
Function with Two Output Parameters
function [L, dx] = Len(p1, p2)
dx = p2 - p1;
L = sqrt(sum(dx.∧2))endfunction
You can use this function in different ways. If you only want thelength and not the projections along the axes-->L = Len([0 0 0], [4 3 0])
L =
5.
When you want to use both output parameters-->[L dxdydz] = Len([0 0 0], [4 3 0])
dxdydz =
3. 4. 5.
L =
5.
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 33 / 38
Scilab Functions
Some Tips and Tricks
Choose names of functions with care
Not too crypticNot too longMeaningful, reflecting the function’s purpose
Choose the input and output arguments after due process of thought
If some input arguments must be of a specified size, do check beforeusing them
If necessary, check the number of input and output parameters at runtime. There is no guarantee that the number of parameters are thesame as the number of arguments
It is allowed to have a variable both as an input and as an outputargument. Typically, such a variable brings in a value in it, getsmodified within the function and the changed value is sent back
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 34 / 38
Scilab Functions
Further Improved Scilab Function
function [L dx] = Len(p1, p2)
[lhs, rhs] = argn()
if rhs < 2 then
disp(’Too few arguments. Returning from function’)
L = 0; dx = [];
return
end
dx = p2 - p1
L = sqrt(sum(dx.∧2))endfunction
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 35 / 38
Scilab Functions
Short Inline Functions
Short functions can be defined inlinedeff(’[L]=Len(p1, p2)’, ’L=sqrt(sum((p2 - p1)∧2))’)
Function deff(string1, string2) takes two strings as inputparameters
First string is the interface to the function, consisting of outputarguments, function name and input arguments
Second string consists of statements making up the body of thefunction
If body contains more than one statement, they must be defined aselements of a vectordeff(’[L]=Len(p1, p2)’, [’dx=p2 - p1’;
’L=sqrt(sum((dx)∧2))’])
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 36 / 38
Scilab Functions
Some Closing Thoughts on Functions
Functions can be called in other functions, and you can build ahierarchy of functions
Simple functions are independent of other user defined functions anddo a simple task efficiently
Complex functions depend on other user defined functions
You can build a library of such functions for a well defined task
image processinggenetic algorithmsstructural optimization
These become toolboxes when packaged in a specified way andbundled along with documentation
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 37 / 38
Scilab Functions
Thank You
Satish Annigeri Ph.D. (BVBCET, Hubli) Scilab Programming 27 Sep, 2010 38 / 38