introduction to scilab 5.3 and xcos - university of cassino
TRANSCRIPT
Introduction to Scilab 5.3 and Xcos
Gianluca Antonelli
Universita degli Studi di [email protected]
http://webuser.unicas.it/lai/roboticahttp://www.docente.unicas.it/gianluca antonelli
Gianluca Antonelli Scilab 5.3
License
Copyright (c) 2011 GIANLUCA ANTONELLI.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.2 orany later version published by the Free Software Foundation; with noInvariant Sections, no Front-Cover Texts, and no Back-Cover Texts.A copy of the license is available at www.gnu.org
Gianluca Antonelli Scilab 5.3
Introduction
The open source platform for numerical computation
Available at http://www.scilab.org
Gianluca Antonelli Scilab 5.3
Running Scilab
From Linux or Windows just selecting the application from theGraphical Menu
From Linux also from the shell typing ./scilab from the correct path
Gianluca Antonelli Scilab 5.3
Scilab command line
Scilab command line is denoted with the symbol
-->
It accepts variables declaration, expressions, script and function calls
Scilab scripts and functions are ASCII files
To re-use a previous command type the up arrow ↑
Gianluca Antonelli Scilab 5.3
Help
help opens a new window where browse for commands and searchkeywords
help name fun opens the help window directly at the pagecorresponding to the function name fun
An on-line help is available http://www.scilab.org/product/man/
A comparison between Matlab/Scilab function inhttp://www.scilab.org/product/dic-mat-sci/M2SCI doc.htm
Gianluca Antonelli Scilab 5.3
Variables
A variable can be defined simply with the syntax
-->name = instruction;
The ; symbol prevents to print on screen the results
Standard rules common to languages as C or Pascal apply for Scilabvariables
Names are case sensitive: a 6=A
To see the variable value just type its name on the prompt or use thetool browsevar()
Gianluca Antonelli Scilab 5.3
Workspace
Variables and functions stay in the workspace
commands of general use are
who
who_user
clear
load
save
diary
browsevar()
Gianluca Antonelli Scilab 5.3
Variable types
A specific set of operators is available for the corresponding type
Common types are
constant , polynomial , function , handle ,
string , boolean , list , rational ,
state -space , sparse , boolean sparse
The type of a variable can be obtained
typeof(variable_name)
Gianluca Antonelli Scilab 5.3
Write protected variables
Certain variables are predefined and write-protected%i i =
√−1 immaginary unit
%pi π = 3.1415927 . . . pi grek%e e = 2.718281 . . . number of Nepero%eps ε = 2.2 · 10−16 precision (machine dependent)%inf infinity%nan NotANumber%s s polynomial variable%z z polynomial variable%t true boolean variable%f false boolean variable
Gianluca Antonelli Scilab 5.3
Matrices
To insert a matrix the syntaxes are
-->A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
-->A = [1, 2, 3
-->4 5 6
-->7,8,9]
A =
1. 2. 3.
4. 5. 6.
7. 8. 9.
Gianluca Antonelli Scilab 5.3
Scalars and vectors
Scalars and vectors are matrices!
-->a=[1 3 5];
-->size(a)
ans =
1. 3.
-->b=3;size(b)
ans =
1. 1.
Gianluca Antonelli Scilab 5.3
Incremental vectors
-->x=1:4
x =
1. 2. 3. 4.
-->x=1:2:10
x =
1. 3. 5. 7. 9.
Also available linspace(x0,xf,npti) and logspace(...)
Gianluca Antonelli Scilab 5.3
Accessing matrix elements
A(i,j) access the element in row i and column j
A(2,4:6) select the columns from 4 to 6 of the second row
B=A(1:3,4:6) assign to B the selected submatrix
A(:,5) select the column 5
A([1 3],5) select a 1x2 vector of two elements: A(1,5) and A(3,5)
Gianluca Antonelli Scilab 5.3
Matrix operations
A wide number of operations are available, in addition to the basicoperations such as sum, product, transpose, matrix esponential,inverse, rank, kernel, etc.
A library of operations are available under the Linear Algebra sectionof the help
Some operations are also defined to be performed on the singleelements of the matrix
Gianluca Antonelli Scilab 5.3
Polynomial operations
Defining a variable as polynomial allows to access several specificoperations
-->my_pol = 3*%s^2 + 2*%s
my_pol =
2
2s + 3s
-->roots(my_pol)
ans =
0
- 0.6666667
Gianluca Antonelli Scilab 5.3
Polynomial operations
Define a polynomial from the coefficient: poly
Define a polynomial from its expression (previous example)
Define a polynomial by operations on elementary polynomials
Extract the coefficients of a polynomial: coeff
Evaluate the polynomial in one single point: horner
Symbolic substitution of the polynomial variable with another
Gianluca Antonelli Scilab 5.3
Rational operations
Rational functions are the division between two polynomials
Several commands defined to their use similar to the polynomial type
Gianluca Antonelli Scilab 5.3
Script
It is a collection of commands saved in a single ASCII file whoseextension is conventionally .sce
It is executed typing
-->exec(’file_name.sce’);
Gianluca Antonelli Scilab 5.3
Functions
A function is a piece of code returning an output given several inputswhose syntax is
function [y1 ,...,ym] = fun(x1 ,...,xn)
commands
endfunction
Several functions can be saved in a single ASCII file whose extensionis conventionally .sci
Gianluca Antonelli Scilab 5.3
Functions
User-defined functions are not available until not explicitely called bygetf(’name file.sci’)
Loading, saving or clearing the variables causes Scilab to do the sameto the functions!
Functions see all the workspace
Inputs are passed by reference if the function does not change theirvalue otherwise by copy
Gianluca Antonelli Scilab 5.3
Programming
Common programming constructions
for, end
while, end
if, then, else, end
select, case, else, end
Logical operators: & | ˜
& and| or˜ not
Gianluca Antonelli Scilab 5.3
Load/Save data
Data in the workspace can be saved in a binary file:save(’name file’)
Data previously saved can be loaded in the workspace:load(’name file’)
C and Fortran-like commands are available to save formatted data inASCII files
Data saved with older version of Matlab can also be loaded
Gianluca Antonelli Scilab 5.3
Graphics
Graphics commands are executed on windows different from the mainone (the Scilex window)
To create a new graphic window
xset(’window ’,num)
scf(num)
General windows-related commands are
clf(num), xclear(num),
xselect(), xdel(num)
Gianluca Antonelli Scilab 5.3
Plot2d
The command plot2d draws bidimentional curves
It uses the current graphic window superimposing the curves
It creates a new graphic window if none is open
Several drawing possibilities depending on the syntax
plot2d ([x],y,<opt_args >)
Gianluca Antonelli Scilab 5.3
Plot2d
plot2d(x,y) where x and y are vectors of the same size draws a curvewith x data in the horizontal and y data in vertical axes
plot2d(y) where y is a vector assumes x=1:n
plot2d(x,y) where x is a vector and y is a matrix assumes the samehorizontal data for the columns of y
plot2d(x,y) where x and y are matrices draws each column of yversus the corresponding column of x
Gianluca Antonelli Scilab 5.3
Plot2d
Let us draw a sinusoidal signal with ω = 5 and phase φ = π/4 for twoperiods
-->w=5;f=%pi/4;tf=(4*%pi -%pi/4)/w;
-->t=linspace(0,tf ,100);plot2d(t,sin(w*t+f))
Refer to the syntax to change colors, add symbols, add labels, title,etc.
Gianluca Antonelli Scilab 5.3
Understanding a graphic window
The graphic window is an object containing several childs: figure,axis, curves
In the previous example the relationship is given by
Figure (1)
- Axes(1)
- Compund(1)
- Polyline(1)
Gianluca Antonelli Scilab 5.3
Modyfing the graphic properties
A GUI opens with the command xset() that allows to change thegraphic context
From the graphic window it is possible to browse the properties of theobjects under the menu [edit]
From a script/function it is possible to have an handle to an objectand modyfing its parameters
h=gcf()
h=gca()
h=gce()
Gianluca Antonelli Scilab 5.3
More axes on the same figure
The subplot(ijk) command divides the figure in a matrix of i rowsand j columns and select the k element
subplot(211); plot2d(ya)
subplot(212); plot2d(yb)
Gianluca Antonelli Scilab 5.3
Exporting your figure
Several commands exist to export your figure such as
xs2eps , xs2fig , xs2gif ,
xs2ppm , xs2ps
and, only for Windows,
xs2bmp , xs2emf
Gianluca Antonelli Scilab 5.3
Dynamic Systems
A powerful tool to the numerical study of
Input-Output dynamic systemsInput-State-Output dynamic systemsFeedback analysisFeedback control design
Gianluca Antonelli Scilab 5.3
Transfer function
-->s=%s;
-->num=1+s;den=(s+2)*(s+3);
-->P=syslin(’c’,num ,den)
P =
1 + s
---------
2
6 + 5s + s
-->typeof(P)
ans =
rational
Gianluca Antonelli Scilab 5.3
Transfer function
-->z=%z;
-->Pd=syslin(’d’,1,z-0.5)
Pd =
1
-------
- 0.5 + z
-->typeof(Pd)
ans =
rational
Gianluca Antonelli Scilab 5.3
State space representation
-->A = [-5 -1
--> 6 0];
-->B = [-1; 1];
-->C = [-1 0];
-->D =0;
-->Sss = syslin(’c’,A,B,C,D)
Gianluca Antonelli Scilab 5.3
State space representation
Sss =
Sss(1) (state -space system :)
!lss A B C D X0 dt !
Sss(2) = A matrix =
- 5. - 1.
6. 0.
Sss(3) = B matrix =
- 1.
1.
Gianluca Antonelli Scilab 5.3
State space representation
Sss(4) = C matrix =
- 1. 0.
Sss(5) = D matrix =
0.
Sss(6) = X0 (initial state) =
0.
0.
Sss(7) = Time domain =
c
-->typeof(Sss)
ans =
state -space
Gianluca Antonelli Scilab 5.3
Conversion ss to/from tf
Conversions are always possible
tf2ss
ss2tf
Conversions are subtles, refer to dynamic systems textbooks
Affected by round-off errors
See minss, minreal
Gianluca Antonelli Scilab 5.3
Extract information from tf
The tf is a rational and all the corresponding functions can be applied:
-->out = roots(P.den)
out =
- 2.
- 3.
Gianluca Antonelli Scilab 5.3
Extract information from ss
Extract, e.g., the dynamic matrix
Sss.A
Extract all matrices
[A,B,C,D]=abcd(Sss);
Gianluca Antonelli Scilab 5.3
Smart view of ss systems
-->ssprint(Sss)
. |-5 -1 | |-1 |
x = | 6 0 |x + | 1 |u
y = |-1 0 |x
Gianluca Antonelli Scilab 5.3
Root locus design
The basic operation needed to design with the root locus tool is tocalculate the value of k that corresponds to a certain point in thelocus:
-->k=-1/real(horner(Stf ,[1,%i]*locate (1)))
locate returns the coordinates of a point in the graphic selected withthe mousehorner computes a rational or polynomial in a given point
Gianluca Antonelli Scilab 5.3
Nichols
The curve is parametrized according to a constant range(!)
Continuous time: [10−3, 103] HzDiscrete time: [10−3, 0.5]
Better to use the whole syntax assigning frequency range:
black(sl , [fmin ,fmax] [,step] [,comments])
Gianluca Antonelli Scilab 5.3
Bode
bode(); gainplot()
Same considerations done for the Nichols diagram
Better to use:
bode(sl, [fmin ,fmax] [,step] [,comments])
Gianluca Antonelli Scilab 5.3
Nyquist
nyquist(); m circle()
Same considerations done for the Nichols and Bode diagrams
Better to use:
nyquist(sl, [fmin ,fmax] [,step] [,comments])
Gianluca Antonelli Scilab 5.3
Horner & Phasemag
horner() evaluates a polynomial/rational in a point
Evaluate F (jω) (in dB and deg) with ω = 5
-->F=syslin(’c’,1,%s+2);
-->out=horner(F,5*%i)
out =
0.0689655 - 0.1724138i
-->[phi ,db]=phasemag(out)
db =
- 14.62398
phi =
- 68.198591
Gianluca Antonelli Scilab 5.3
A final bird’s-eye view
Stability margins (g margin, p margin)
Continuous-discrete time conversion (cls2dls)
Simple numerical simulation of dynamics systems
Numerical resolution of differential equations (ode)
Observability, controllability, Kalman filter
Controller design commands
Gianluca Antonelli Scilab 5.3
Xcos
Graphical dynamic system simulator
Library of blocks
Continuous/discrete time systemsAdd custom blocks in C/Fortran/ScilabGenerate C codeReal-time HIL testsHard real-time executable
Gianluca Antonelli Scilab 5.3
Run Xcos
Within the Scilab environment
From the command prompt --> xcos
Menu -> Applications -> Xcos
Gianluca Antonelli Scilab 5.3
Continuous time on a PC?
Xcos emulates continuous-time dynamic systems via numericalalgorithms (see discretization on textbooks)
Conceptually similar to the differential vs difference equations
In alternative Xcos executes blocks when an activation input is given
Activation signals are used also for discrete-time systems
Gianluca Antonelli Scilab 5.3
What is a block?
A graphical function with (eventual)
InputStateOutputScalar/vectorial quantitiesContinuous/discrete timeActivation inputsActivation outputs
Gianluca Antonelli Scilab 5.3
What is a superblock?
Is a block containing other blocks
Same concept as functions inside other functionsImprove readability of the diagram
Gianluca Antonelli Scilab 5.3
A basic diagram
Drag-and-drop a source. . . a transfer function and a scope
Gianluca Antonelli Scilab 5.3
Blocks’ parameters
Avoid the use of constants in the blocks’ parameters
Use variables instead:
put all the variables in a file (var.sce)open Diagram -> Context and write exec(’var.sce’)
use the variables in the blocks
In alternative global variables
Gianluca Antonelli Scilab 5.3
Importing data
From proper blocks
Reading from binary or formatted files
From the workspace
Gianluca Antonelli Scilab 5.3
Exporting data
To graphic windows (scope. . . )
To binary or formatted files
To the workspace
Specific graphic output for matrices
Gianluca Antonelli Scilab 5.3