Está en la página 1de 35

UNIVERSIDAD DEL VALLE

FACULTAD DE INGENIERIA

ESCUELA DE INGENIERIA ELECTRICA Y ELECTRONICA

MANUAL BASICO INTRODUCTORIO AL SCILAB

POR

ING. EDINSON FRANCO MEJIA, M.Sc.

CARLOS A. RAMOS PAJA, Estudiante Ing. Electrónica

GRUPO DE INVESTIGACION EN CONTROL INDUSTRIAL

GICI

SANTIAGO DE CALI

MARZO DEL 2000


CAPITULO I. MATERIAL DE INTRODUCCIÓN

" SCILAB is a package which offers functionalities comparable to MATLAB, with some additional
features such as METANET, which is concerned with graphs and networks.

SCILAB has been developed in the META2 project of INRIA-Rocquencourt for years and is currently
distributed as a freeware with sources (see the SCILAB official page).

Recently, we have added new capabilities to perform matrix computations in other algebras
(presently, the MaxPlus and MinPlus algebras) and thus, to develop system related operations for
discrete event systems which are relevant to these algebras.

The audience may consist of mathematicians, (control) engineers, physicists, computer scientists
from graduate students to experts who want to learn a new tool. The expected background is a
knowledge of basic linear algebra. Some knowledge of the MaxPlus algebra is helpful but not
required. The package is (very) user friendly so (virtually) no knowledge of "computers" (e.g. OS) is
1
needed. ..."

1. INTRODUCCIÓN

Scilab es un paquete matemático desarrollado por INRIA. Scilab tiene compatibilidad para
programación en C y fortran, posee manipulación de matrices, calculo simbólico y muchas otras
aplicaciones matemáticas.

La filosofía general de scilab se basa en proporcionar un entorno computacional para :

Tener tipos de datos flexibles, con sintaxis natural y facil de usar.

• Disponer de una razonable cantidad de primitivas para realizar gran variedad de cálculos.
• Tener un sistema de desarrollo donde sea facial adicionar nuevas primitivas. Una herramienta de
desarrollo facil de usar distribuida con SCILAB es INTERSCI, desarrollada para crear primitivas y
interfaces, adicionar módulos de Fortran y C a SCILAB, etc.
• Soportar librerías de desarrollo (toolboxes) de funciones desarrolladas para aplicaciones especificas,
tales como: control lineal, control no-lineal, procesamiento de señales, etc.
• Poseer una ayuda en linea con el comando help.

Los instaladores de SCILAB y los manuales (si usted se encuentra en la red Farallones ) están
disponibles en ftp://eiee.univallle.edu.co/pub/scilab y en ftp://malagana.univallle.edu.co/pub/scilab ,
la información original o/y los FAQ, los puede bajar desde http://www-rocq.inria.fr/scilab .

Esta introducción se ha realizado tomando la anterior información como referencia, en su lectura


encontrará muchas combinaciones de información en español y otras en Ingles, se ha procurado
dejar algunas referencias tal y como las encuentran en los “help” del paquete para ayudar a que el
estudiante se familiarice con textos en Ingles.

1
Tomado de http://www.inria.fr/Colloques/ALAPEDESSCILAB-eng.html
2. ESTRUCTURA DEL PROGRAMA

SCILAB esta estructurado en directorios muy específicos tales como:

bin : Es el directorio de los ejecutables.

• demos : Se encuentran archivos de ejemplo de uso del paquete.


• examples : Aquí están los ejemplos de como adicionar programas externos a SCILAB, usando
enlace dinámico o INTERSCI.
• doc : Manuales y archivos de ayuda están aquí, también puede ver las ayudas en linea con el
comando help.
• geci : En este directorio esta el código fuente y los binarios de GeCI, que es un administrador
interactivo de comunicaciones creado para controlar conexiones remotas de programas. Esto
permite tener una maquina virtual de proyecto en varios sistemas.
• pvm3 : Contiene otro administrador interactivo de comunicaciones PVM versión 3.
• imp : Están aquí los archivos de impresión en Postscript.
• macros : Aquí están los "Toolboxes" para aplicaciones especificas. Adicionar "Toolboxes" es muy
sencillo.
• man : Están los archivos de ayuda y manuales variados.
• maple : Aquí se encuentran las funciones para adicionar objetos al SCILAB, por eficiencia se
genera codigo FORTRAN para enlazarlo con SCILAB.
• routines : Están aquí el código fuente de las rutinas numéricas.
• intersci : Contiene una interfaz para adicionar primitivas en C o Fortran a SCILAB.
• scripts : Aquí esta el código fuente de los scripts shell.
• tests : Este directorio contiene archivos para probar la instalación del SCILAB.
• util : Aquí están varias utilidades usadas por SCILAB como sub-funciones.
• xless : Utilidad de búsqueda de archivos de Berkeley.
• xmetanet : Aquí esta XMETANET, un graficador para redes. Para usarlo en el prompt del SCILAP
tipee metanet().

3. INICIANDO

Esta introducción está diseñada sobre la versión para windows, en realidad los cambios con
respecto a la versión para Linux son pocos , cambia un poco el entorno gráfico pero las
instrucciones y comandos siguen siendo los mismos.

Luego de descompactar el SCILAB, en la linea de comandos, solo teclee scilab y enter, usted verá
una ventana, en donde se ve el siguiente mensaje, y se genera una linea de comandos ->:
FIGURA 1. Interface Gráfica de la versión Scilab2.5 para Windows

La primera interacción con SCILAB se logra fácilmente dando click en el botón File y Demos para la
versión bajo Windows o simplemente DEMOS para la versión bajo Linux, o tecleando demos en la
linea de comandos, en esta ventana se encuentran otros botones cuyas funciones son:

a) Para Windows

FILE: aquí se controla el sistema de archivos y se pueden cargar y guardar archivos de scilab, llamar
funciones predefinidas, en general manipular archivos e históricos y se puede salir del SCILAB.
FUNCTIONS: Permite manipular funciones definidas por el usuario, ver las funciones de control de
flujo de información o comandos (what), muy útil cuando se escriben funciones, y ver las variables
empleadas en la sesión ( comando who).
HELP: Proporciona ayuda en línea sobre comandos e instrucciones.
RESTART, PAUSE y RESUME: De aquí se pueden controlar los estados de la simulación, con stop
o pause se detiene una simulación, la cual se reanuda con resume. Restart Permite reiniciar la
sesión de Scilab sin cerrar la aplicación, toda las variables y funciones generadas hasta el momento
se perderán si no se salvan, similar a realizar un clear().
ABORT, INTERRUP: Permiten el control de tareas básicas de simulación como su nombre lo indica,
la abortaran o interrumpirán dependiendo de su elección.
GRAFIC_WINDOW 0: Permite el control de la ventana de gratificación

b) Para Linux

FILE: aquí se controla el sistema de archivos y se pueden cargar y guardar archivos de scilab, y se
puede salir del SCILAB.
CONTROL: De aquí se pueden controlar los estados de la simulación, con stop o pause se detiene
una simulación, la cual se reanuda con resume.
GRAFIC_WINDOW 0: Permite el control de la ventana de gratificación

4. INTERPRETACION DE LAS AYUDAS

La mayoría de esta información ha sido extractada a través de las ayudas del Scilab y los
documentos originales, la estructura del help es la siguiente
NOMBRE DE LA FUNCIÓN (xxxx)- Descripción del nombre

CALLING SEQUENCE
xxxx (a,b,...,[A1,A2, ...,An])

PARAMETERS

a,b,... : argumentos de entrada

A1, A2,...An : Argumentos opcionales

DESCRIPTION
aquí hay una descripción de la función

EXAMPLE
aquí encuentran uno o varios ejemplos de uso de la función

SEE ALSO
aquí encuentran referencias a otros comandos similares o asociados

AUTHOR
aquí se referencia el(los) nombre(s) del (os) autor (es).

Ejemplo 1.0: Veamos el help del help de Scilab

help(1) Scilab Function help(1)

NAME
help - on-line help command

CALLING SEQUENCE
help word

DESCRIPTION
To each documented word corresponds a word.cat ascii file. these files are
organised within directories (chapters). Each chapter must contain *.cat
files and a whatis file with one line for each documented word in the chap-
ter. Each line must have the following format :

word - quick description

List of chapter directories is given in a file (whose path is given in the


$MANCHAPTERS environment variable) with the following format for each chap-
ter:

chapter_path chapter_title
MANCHAPTERS default value is SCI/man/Chapters. If you want to add new help
chapters you have to do a copy of the SCIDIR/man/Chapters file where you
want, to add descriptions lines for each new chapter and to define the new
value of MANCHAPTERS environment variable.

See also Scilab's manual

SEE ALSO
apropos
CAPITULO II.2 COMANDOS BASICOS
- APRENDIENDO A TRAVÉS DE EJEMPLOS -

1. TIPOS DE DATOS

1.1 Constantes Especiales

SCILAB tiene algunas constantes predefinidas tales como:

%i = Imaginarion la raiz cuadrada de -1


%pi = Numero PI = 3.141592...
%e = Numero e exponencial
%eps = Numero tal que 1+%eps = 1
%s = Variable simbolica para s=poly(0,'s')
%z = Variable simbolica para z=poly(0,'z')
%t = Valor booleano verdadero
%f = Valor booleano falso

El simbolo % es empleado para indicar variables pretipeadas

1.2 Matrices y Vectores

• Para definir un vector:

--> v=[1 5 6]
v=
! 1. 5. 6. !

--> ones(v)
ans =
! 1. 1. 1. !

--> ones(v') //La comilla se usa para indicar inversión de la matriz o vector
ans =
! 1. !
! 1. !
! 1. !

Para definir matrices:

--> A=[2 1 4;5 -8 2]


A=
! 2. 1. 4. !
! 5. - 8. 2. !

--> b=ones(2,3)

2
Tomado de los documentos del Scilab, corresponde a parte del primer demo.
b=
! 1. 1. 1. !
! 1. 1. 1. !

--> A.*b
ans =
! 2. 1. 4. !
! 5. - 8. 2. !

--> A*b'
ans =
! 7. 7. !
! - 1. - 1. !

1. MANIPULACIÓN DE DATOS.

En general Scilab los denomina como Objetos y pueden ser escalares, Matrices y listas. Su
definición y manipulación se ilustra a continuación:

NOTA 1: Al igual que en Matab, la inclusión de un carácter punto y coma (“;”) al final de la línea
elimina el eco.

2.1 Escalares

-->a=1; //constante real


-->1==1 //booleano
ans = T

-->'string' //cadena de caracteres


ans = string

-->z=poly(0,'z') // polinomio con variable 'z' y con una raiz en cero


z =z

-->p=1+3*z+4.5*z^2 //polinomiol
2
p = 1 + 3z + 4.5z

-->r=z/p //racional

z
r= -------------
2
1 + 3z + 4.5z
2.2 Matrices

NOTA2: Observe como las matrices se organizan en filas y columnas, para cambio de fila se puede
empear el “enter” de su teclado o el carácter “;”. La matriz puede contener variables predefinidas
como se ilustra a continuación, tambien puede contener datos prototipeados como por ejemplo las
constantes especiales vistas al principio.

-->A=[a+1 2 3
--> 0 0 atan(1)
--> 5 9 -1 ] //matriz constante 3x3
A =
! 2. 2. 3. !
! 0. 0. 0.7853982 !
! 5. 9. - 1. !

-->Mc=['this','is';
--> 'a' ,'matrix'] //matrix of caracteres 2x2
Mc =
!this is !
! !
!a matrix !

-->Mp=[p,1-z;
--> 1,z*p] /matriz polinomial 2x2

Mp =
! 2 !
! 1 + 3z + 4.5z 1-z !
! !
! 2 3!
! 1 z + 3z + 4.5z !

-->Sp=sparse([1,2;4,5;3,10],[1,2,3]) //matriz sparse

Sp =
( 4, 10) sparse matrix
( 1, 2) 1.
( 3, 10) 3.
( 4, 5) 2.

-->Sp(1,10)==Sp(1,1) //matriz sparce booleana

ans =
( 1, 1) sparse matrix
( 1, 1) T
2.3 Listas

-->L=list(a,-(1:5), Mp,['this','is';'a','list']) //lista


L =

L(1)
1.

L(2)

! - 1. - 2. - 3. - 4. - 5. !

L(3)

! 2 !
! 1 + 3z + 4.5z 1-z !
! !
! 2 3!
! 1 z + 3z + 4.5z !

L(4)

!this is !
! !
!a list !

-->L(2)(3) //sub-entrada en lista


ans =

- 3.

-->Lt=tlist(['mylist','color','position','weight'],'blue',[0,1],10) //lista tipeda


Lt =

Lt(1)

!mylist color position weight !

Lt(2)

blue

Lt(3)

! 0. 1. !
Lt(4)

10.

-->Lt('color') //extractando un dato


ans =

blue

-->Lt('weight') //extractando un dato


ans =

10.

3. OPERACIONES

3.1 Con escalares

• Suma simple

-->a=1;
-->A=2;

-->a+A
ans=
3.

Varios Comandos pueden incluirse en la misma linea separados por “;”

-->a=1; A=2; a+A


ans=
3.

• Se pueden formar ecuaciones y obtener resultados numéricos

-->a=1; b=1.5; 2*a+b^2


ans=
4.25.

• Manipulación de escalares racionales

-->a=2; b=3;

-->a/b
ans=
0.6666667
-->b/a
ans=
1.5

-->s=%s; p=2*s+3*s*s*+7; q=s+1;


-->q/p
ans=
s+1
--------------
3s²+2s+7

3.2 Con matrices

• Matriz Inversa
-->inv(A)
ans =

! 0.5 0. 0. !
! 0. 0.3333333 0. !
! 0. 0. 0.25 !

• Transpuesta de una matriz A


-->B=[ 1 2 3
456
7 8 9];
-->B'
ans =

! 1 4 7!
! 2 5 8!
! 3 6 9!

• Generando una matriz de unos


-->u=ones(2,4)
ans=
!1 1 1 1!
!1 1 1 1!

• Generando una matriz de ceros


-->u=zeros(3,5)
ans=
!0 0 0 0 0 !
!0 0 0 0 0 !
!0 0 0 0 0 !

• Multiplicación de matriz constante


-->v=1:5;W=v' * v
W =

! 1. 2. 3. 4. 5. !
! 2. 4. 6. 8. 10. !
! 3. 6. 9. 12. 15. !
! 4. 8. 12. 16. 20. !
! 5. 10. 15. 20. 25. !

-->W(1,:) // sacando la primera fila


ans =

! 1. 2. 3. 4. 5. !

-->W(:,$) //sacando la última columna


ans =

! 5. !
! 10. !
! 15. !
! 20. !
! 25. !

• Manipulando matrices polinomiales


-->Mp'*Mp+eye()
ans =

column 1

! 2 3 4 !
! 3 + 6z + 18z + 27z + 20.25z !
! !
! 2 !
! 1 + 3z + 4.5z !

column 2

! 2 !
! 1 + 3z + 4.5z !
! !
! 2 3 4 5 6 !
! 2 - 2z + 2z + 6z + 18z + 27z + 20.25z !

• Generando una matriz compleja


-->Mp1=Mp(1,1)+4.5*%i
Mp1 =

parte real
2
1 + 3z + 4.5z

parte imaginaria
4.5

• Manipulación de matrices para evaluar una función de transferencia


-->Fi=C*(z*eye()-A)^(-1)*B;

• Manipulación de matrices racionales

Ejercicio 2.1: Dadas las matrices c=[1 2] y M=[q p] donde p=2*s+3*s*s*+7 y q=s+1, realice las
siguientes operaciones, analice y concluya:

-->c/M
-->M/c
-->c’/M
-->c/M’
-->M’/c
-->M/c’

3. GENERANDO Y MANIPULANDO LAS OPCIONES DE GRAFICACION

Por ser las herramientas gráficas de mucha utilidad en ingenierías, este es uno de los campos mas
dinámicos, hay nuevos aportes en funciones y macros. A continuación se hará una descripción
básica de los comandos mas simples disponibles en Scilab.

Se puede obtener una descripción de las herramientas de graficación en el help de “Graphics -


graphics library overview”, que se lista a continuación

graphics(2)
Scilab Function graphics(2)
NAME

2D PLOTTING

plot : simple plot of a curve


plot2d : plot a curve
plot2d1 : plot a curve, allows logarithmic axes
plot2d2 : plot a curve as step function
plot2d3 : plot a curve with vertical bars
plot2d4 : plot a curve with arrows
fplot2d : plot a curve defined by a function
champ : 2D vector field
champ1 : 2D vector field with colored arrows
fchamp : direction field of a 2D first order ODE
contour2d : level curves of a surface on a 2D plot
fcontour2d : level curves of a surface defined by a function on a 2D plot
grayplot : 2D plot of a surface using colors
fgrayplot : 2D plot of a surface defined by a function using colors
Sgrayplot : smooth 2D plot of a surface using colors
Sfgrayplot : smooth 2D plot of a surface defined by a function using colors
xgrid : add a grid on a 2D plot
errbar : add vertical error bars on a 2D plot
histplot : plot a histogram
Matplot : 2D plot of a matrix using colors

3D PLOTTING

plot3d : plot a surface


plot3d1 : plot a surface with gray or color level
fplot3d : plot a surface defined by a function
fplot3d1 : plot a surface defined by a function with gray or color level
param3d : plot one curve
param3d1 : plots curves
contour : level curves on a 3D surface
fcontour : level curves on a 3D surface defined by a function

hist3d : 3D representation of a histogram


genfac3d : compute facets of a 3D surface
eval3dp : compute facets of a 3D surface
geom3d : projection from 3D on 2D after a 3D plot

LINE AND POLYGON PLOTTING

xpoly : draw a polyline or a polygon


xpolys : draw a set of polylines or polygons
xrpoly : draw a regular polygon
xsegs : draw unconnected segments
xfpoly : fill a polygon
xfpolys : fill a set of polygons

RECTANGLE PLOTTING

xrect : draw a rectangle


xfrect : fill a rectangle
xrects : draw or fill a set of rectangles

ARC PLOTTING

xarc : draw a part of an ellipse


xarcs : draw parts of a set of ellipses
xfarc : fill a part of an ellipse
xfarcs : fill parts of a set of ellipses

ARROW PLOTTING

xarrows : draw a set of arrows

STRINGS
xstring : draw strings
xstringl : compute a box which surrounds strings
xstringb : draw strings into a box
xtitle : add titles on a graphics window
titlepage : add a title in the middle of a graphics window
xinfo : draw an info string in the message subwindow

FRAMES AND AXES

xaxis : draw an axis


graduate : pretty axis graduations
plotframe : plot a frame with scaling and grids

COORDINATES TRANSFORMATIONS

isoview : set scales for isometric plot (do not change the size of the
window)
square : set scales for isometric plot (change the size of the window)

scaling : affine transformation of a set of points


rotate : rotation of a set of points
xsetech : set the sub window of a graphics window for plotting
xgetech : get the current graphics scale
xchange : transform real to pixel coordinates

COLORS

colormap : using colormaps


getcolor : dialog to select colors in the current colormap
addcolor : add new colors to the current colormap
graycolormap
: linear gray colormap
hotcolormap
: red to yellow colormap

GRAPHICS CONTEXT

xset : set values of the graphics context


xget : get current values of the graphics context
xlfont : load a font in the graphics context or query loaded font
getsymbol : dialog to select a symbol and its size

SAVE AND LOAD

xsave : save graphics into a file


xload : load a saved graphics
xbasimp : send graphics to a Postscript printer or in a file
xs2fig : send graphics to a file in Xfig syntax

GRAPHICS PRIMITIVES

xbasc : clear a graphics window and erase the associated recorded


graphics
xclear : clear a graphics window
driver : select a graphics driver
xinit : initialisation of a graphics driver
xend : close a graphics session
xbasr : redraw a graphics window
replot : redraw the current graphics window with new boundaries
xpause : suspend Scilab
xselect : raise the current graphics window
xclea : erase a rectangle
xclip : set a clipping zone
xdel : delete a graphics window
winsid : return the list of graphics windows
xname : change the name of the current graphics window

MOUSE POSITION

xclick : wait for a mouse click


locate : mouse selection of a set of points

xgetmouse : get the current position of the mouse

INTERACTIVE EDITOR

edit_curv : interactive graphics curve editor


gr_menu : simple interactives graphic editor
sd2sci : gr_menu structure to scilab instruction convertor

GRAPHICS FUNCTIONS FOR AUTOMATIC CONTROL

bode : Bode plot


gainplot : magnitude plot
nyquist : Nyquist plot
m_circle : M-circle plot
chart : Nichols chart
black : Black's diagram
evans : Evans root locus
sgrid : s-plane grid lines
plzr : pole-zero plot
zgrid : zgrid plot

3.1 Algunos ejemplos

• Graficación simple de una y dos funciones en 2D

Para esto se usa el comando plot, cuya secuencia de llamada es :

plot(x,y,[xcap,ycap,caption])
plot(y)
PARAMETERS

x,y : two vectors with same sizes

xcap,ycap,caption
: character strings or string matrices

DESCRIPTION
Plot y as function of x. xcap and ycap are captions for x-axis and y-axis
respectively and caption is the caption of the plot.

Invoked with only one argument, plot(y) plots the y vector or, if y is a
matrix, it plots all its row vectors on the same plot. This plot is done
with respect to the vector 1:<number of columns of y>.

For more complex plotting, use plot2d.

EXAMPLE
x=0:0.1:2*%pi; // genera señal x correspondiente a angulos de 0 a 2 pi , espaciadas 0.1 rad/seg
plot(sin(x)) // realiza el gráfico simple de la fiunción seno, ver Figura 2

plot(x,sin(x),"sin","time","plot of sinus") // sin(x) v.s. x con los titulos en los ejes de abcisas y
ordenadas, ver Figura 3

xbasc() // permite limpiar la ventana de graficación


plot([sin(x);cos(x)]) // grafica simultaneamente el seno y el coseno, ver Figura 4

SEE ALSO
plot2d

AUTHOR
J.Ph.C.
FIGURA 2. Graficación de sin(x), donde x=0:0.1:2*%pi;

FIGURA 3. Graficación de sin(x) v.s. x con titulos, donde x=0:0.1:2*%pi;


FIGURA 4. Graficación de sin(x) v.s. x y cos(s) v.s. x , donde x=0:0.1:2*%pi;

• Graficación en de multiples ventanas en 2D


Pendiente

• Graficación en 3D
Pendiente
CAPITULO III. COMANDOS PARA SIMULACION EN CONTROL .
- APRENDIENDO A TRAVÉS DE EJEMPLOS -

GENERANDO FUNCIONES Y SISTEMAS

NOTA 3: En control se definen los sistemas dependiendo del dominio del tiempo como dsicretos o
continuos, la representacion puede hacerse en funcion de transferencia, o en el espacio de estados.

Caso a: Sistemas representados como función de transferencia

Ejemplo 3.1 Sea el sistema:

sA2
G ¢s £=
s ¢ sA3£ ,

lo primero que se debe hacer es definir la variable s, existen dos maneras:


1- s=poly(0,'s' ) ó
2- s=%s

posteriormente debe escribir la función de transferencia G(s) como:

--> Gs=(s+2)/(s*(s+3));

finalmente debe formar un sistema lineal con la función escrita para que el scilab la interprete

--> Gsl=syslin('c',Gs )

NOTA 4: No siempre es necesario generar el sistema lineal, en linux si lo debe hacer , en Windows
es opcional, recomiendo acostumbrar hacerlo.

Observese que el primer argumento de la función syslin es un caracter “c” que indica que el sistema
es de tiempo contínuo, para sistemas de tiempo discreto usaremos el carácter “d”.

Una forma abreviada de hacer lo mismo es digitando en una linea:

--> s=%s; Gsl=('c', (s+2)/(s*(s+3)));

Ejemplo 3.2 Sea el sistema:

zA0.1153
G ¢ z £=1.7788
¢ zB1£ ¢ zB0.1089£ ,

lo primero que se debe hacer es definir la variable z, existen dos maneras:

1- z=poly(0,'z' ) ó
2- z=%z

posteriormente debe escribir la función de transferencia G(z) como:


--> Gz=1.7788*(z+0.1153)/((z-1)*(z-0.1089));

finalmente debe formar un sistema lineal con la función escrita para que el scilab la interprete

--> Gzl=syslin('d',Gz )

Una forma abreviada de hacer lo mismo es digitando en una linea:

--> z=%z; Gzl=('d', 1.7788*(z+0.1153)/((z-1)*(z-0.1089)));

Caso b: Sistemas representados en el espacio de estados

En general, usted puede revisar la información sobre la función syslin a través del comando help
syslin, a continuación se reimprimen estos datos:

syslin(1) Scilab Function syslin(1)

NAME
syslin - linear system definition

CALLING SEQUENCE
[sl]=syslin(dom,A,B,C [,D [,x0] ])
[sl]=syslin(dom,N,D)
[sl]=syslin(dom,H)

PARAMETERS

dom : character string ('c', 'd'), or [] or a scalar.

A,B,C,D : matrices of the state-space representation (D optional with


default value zero matrix). For improper systems D is a polyno-
mial matrix.

x0 : vector (initial state; default value is 0)

N, D : polynomial matrices

H : rational matrix or linear state space representation

sl : tlist ("syslin" list) representing the linear system

DESCRIPTION
syslin defines a linear system as a list and checks consistency of data.

dom specifies the time domain of the system and can have the following val-
ues:

dom='c' for a continuous time system, dom='d' for a discrete time system, n
for a sampled system with sampling period n (in seconds).
dom=[] if the time domain is undefined

State-space representation:
sl=syslin(dom,A,B,C [,D [,x0] ])
represents the system :
s x = A*x + B*u
y = C*x + D*u

x(0) = x0
The output of syslin is a list of the following form:

sl=tlist(['lss','A','B','C','D','X0','dt'],A,B,C,D,x0,dom)

Note that D is allowed to be a polynomial matrix (improper systems).

Transfer matrix representation:


sl=syslin(dom,N,D)
sl=syslin(dom,H)
The output of syslin is a list of the following form :
sl=tlist(['r','num','den','dt'],N,D,dom) or
sl=tlist(['r','num','den','dt'],H(2),H(3),dom).

Linear systems defined as syslin can be manipulated as usual matrices (con-


catenation, extraction, transpose, multiplication, etc) both in state-space
or transfer representation.

Most of state-space control functions receive a syslin list as input


instead of the four matrices defining the system.

Ejemplo 3.3 Definición de un dos sistemas lineales en variables de estado y su operación como
sistemas en pararalelo

A=[0,1;0,0];B=[1;1];C=[1,1];
S1=syslin('c',A,B,C) //Linear system definition
S1("A") //Display of A-matrix
S1("X0"), S1("dt") // Display of X0 and time domain
s=poly(0,'s');
D=s;
S2=syslin('c',A,B,C,D)
H1=(1+2*s)/s^2, S1bis=syslin('c',H1)
H2=(1+2*s+s^3)/s^2, S2bis=syslin('c',H2)
S1+S2
[S1,S2]
ss2tf(S1)-S1bis
S1bis+S2bis
S1*S2bis
size(S1)
Ejercicio 3.1. Ingrese al Scilab el siguiente sistema de control en tiempo discreto discreto
representado en variables de estado ? (Tomado del ejemplo 10.24 de Sistemas de Control Digital de
Benjamin Kuo, 1a edición en Español)

x¦¢kA1£ T §=Ax¢kT £ABu¢kT £; y¢kT =Cx ¢kT £ADu¢kT£

A=[0 1; -1 -2]; B=[1 0;0 1]; C=[1 0]; D=0


Caso c: Paso de espacio de estados a función de transferencia y viceversa

Para transferir sistemas representados en función de transferencia a espacio de estados se emplea


la instrucción:

tf2ss - transfer to state-space

CALLING SEQUENCE
sl=tf2ss(h [,tol])

PARAMETERS

h : rational matrix

tol : may be the constant rtol or the 2 vector [rtol atol]

rtol :tolerance used when evaluating observability.

atol :absolute tolerance used when evaluating observability.

sl : linear system (syslin list sl=[A,B,C,D(s)])

DESCRIPTION
transfer to state-space conversion:

h=C*(s*eye()-A)^-1*B+D(s)

Ejemplo 3.4

s=poly(0,'s');
H=[2/s,(s+1)/(s^2-5)];
Sys=tf2ss(H)
clean(ss2tf(Sys))

Para transferir sistemas representados en espacio de estados a función de transferencia se emplea


la instrucción:

ss2tf - conversion from state-space to transfer function

CALLING SEQUENCE
[h]=ss2tf(sl)
[Ds,NUM,chi]=ss2tf(sl)

PARAMETERS
sl : linear system (syslin list)

h : transfer matrix

DESCRIPTION
Called with three outputs [Ds,NUM,chi]=ss2tf(sl) returns the numerator
polynomial matrix NUM, the characteristic polynomial chi and the polynomial
part Ds separately i.e.:
h=NUM/chi + Ds

Method:

One uses the characteristic polynomial and det(A+Eij)=det(A)+C(i,j) where C


is the adjugate matrix of A.

Ejemplo 3.5
s=poly(0,'s');
h=[1,1/s;1/(s^2+1),s/(s^2-2)]
sl=tf2ss(h);
h=clean(ss2tf(sl))
[Ds,NUM,chi]=ss2tf(sl)

SIMULANDO SISTEMAS DE CONTROL ANTE SEÑALES DE ENTRADA TIPICAS

En la sección anterior vimos como se define un sistema lineal, para analizar su desempeño ante
señales de entrada típicas impulso ó escalón o cualquier otro tipo de señal se dispone del comando
csim() para simular sistemas continuos y del comando dsim() para simular sistemas discretos. A
continuación una descripción de estas funciones :

Caso a. Simulación de sistemas representados en variable compleja

csim - simulation (time response) of linear system

CALLING SEQUENCE
[y [,x]]=csim(u,t,sl,[x0])

PARAMETERS

u : function, list or string (control)

t : real vector specifying times with, t(1) is the initial time


(x0=x(t(1))).

sl : list (syslin)
y : a matrix such that y=[y(t(i)], i=1,..,n

x : a matrix such that x=[x(t(i)], i=1,..,n

DESCRIPTION
simulation of the controlled linear system sl. sl is assumed to be a con-
tinuous-time system represented by a syslin list.

u is the control and x0 the initial state.

y is the output and x the state.

The control can be:

1. a function : [inputs]=u(t)

2. a list : list(ut,parameter1,....,parametern) such that:


inputs=ut(t,parameter1,....,parametern) (ut is a function)

3. the string "impuls" for impulse response calculation (here sl is assumed


SISO without direct feed through and x0=0)

4. the string "step" for step response calculation (here sl is assumed SISO
without direct feed-through and x0=0)

Ejemplo 3.6

s=poly(0,'s');rand('seed',0);w=ssrand(1,1,3);w('A')=w('A')-2*eye();
t=0:0.05:5;
//impulse(w) = step (s * w)
xbasc(0);xset("window",0);xselect();
plot2d([t',t'],[(csim('step',t,tf2ss(s)*w))',0*t'])
xbasc(1);xset("window",1);xselect();
plot2d([t',t'],[(csim('impulse',t,w))',0*t'])
//step(w) = impulse (s^-1 * w)
xbasc(3);xset("window",3);xselect();
plot2d([t',t'],[(csim('step',t,w))',0*t'])
xbasc(4);xset("window",4);xselect();
plot2d([t',t'],[(csim('impulse',t,tf2ss(1/s)*w))',0*t'])

dsimul - state space discrete time simulation

CALLING SEQUENCE
y=dsimul(sl,u)

PARAMETERS

sl : syslin list describing a discrete time linear system

u : real matrix of appropriate dimension


y : output of sl

DESCRIPTION
Utility function. If [A,B,C,D]=abcd(sl) and x0=sl('X0'), dsimul returns
y=C*ltitr(A,B,u,x0)+D*u i.e. the time response of sl to the input u. sl
is assumed to be in state space form (syslin list).

EXAMPLE
z=poly(0,'z');
h=(1-2*z)/(z^2-0.2*z+1);
sl=tf2ss(h);
u=zeros(1,20);u(1)=1;
x1=dsimul(sl,u) //Impulse response
u=ones(20,1);
x2=dsimul(sl,u); //Step response

SEE ALSO
syslin, flts, ltitr

Ejemplo 3.7
z=poly(0,'z');
h=(1-2*z)/(z^2-0.2*z+1);
sl=tf2ss(h);
u=zeros(1,20);u(1)=1;
x1=dsimul(sl,u) //Impulse response
u=ones(20,1);
x2=dsimul(sl,u); //Step response

NOTA: Existen otras herramientas útiles para simular sistemas discretos tales como: flts(), ltitr() y
rtitr() se deja al lector como ejercicio revisar estas funciones

Ejemplo 3.8 Análisis de un sitema de segundo orden

-->sl=syslin('c',1/(s*s+0.2*s+1))
sl =

1
---------------
2
1 + 0.2s + s

-->instants=0:0.05:20;

-->// step response:

-->y=csim('step',instants,sl);

-->xbasc();plot2d(instants',y')
-->// Delayed step response

-->deff('[in]=u(t)','if t<3 then in=0;else in=1;end');

-->y1=csim(u,instants,sl);plot2d(instants',y1');

-->// Impulse response;

-->yi=csim('imp',instants,sl);xbasc();plot2d(instants',yi');

-->yi1=csim('step',instants,s*sl);plot2d(instants',yi1');

-->// Discretization

-->dt=0.05;

-->sld=dscr(tf2ss(sl),0.05);

-->// Step response

-->u=ones(instants);
Warning :redefining function: u

-->yyy=flts(u,sld);

-->xbasc();plot(instants,yyy)

-->// Impulse response

-->u=0*ones(instants);u(1)=1/dt;

-->yy=flts(u,sld);

-->xbasc();plot(instants,yy)

-->// system interconnexion

-->w1=[w,w];

-->clean(ss2tf(w1))

ans =

! 1 1 1 1 !
! - ------- --- -------- !
! s 1+s s 1+s !
! !
! 1 1 1 1 !
!----- --- ----------- ------- --------- !
! 2 2 2 2 !
!s+s 4 + 4s + s s+s 4 + 4s + s !

-->w2=[w;w];

-->clean(ss2tf(w2))
ans =

! 1 1 !
! - ------ !
! s 1+s !
! !
! 1 1 !
! ----- --------------- !
! 2 2 !
! s+s 4 + 4s + s !
! !
! 1 1 !
! - ----- !
! s 1+s !
! !
! 1 1 !
! ----- --------------- !
! 2 2 !
! s+s 4 + 4s + s !

-->// change of variable

-->z=poly(0,'z');

-->horner(h,(1-z)/(1+z)) //bilinear transform


ans =

! 1+z 1+z !
! ----- ----------- !
! 1-z 2 !
! !
! 2 2!
! 1 + 2z + z 1 + 2z + z !
!----------------- ---------------- !
! 2!
! 2 - 2z 9 + 6z + z !

Caso b. Solución de ecuaciones diferenciales ordinarias

Para resolver ecuaciones diferenciales ordinarias Scilab introduce una herramienta conocida como
“ode”
ode(G) Scilab Function ode(G)
NAME
ode - ordinary differential equation solver

CALLING SEQUENCE
y=ode(y0,t0,t,f)
[y,w,iw]=ode([type],y0,t0,t [,rtol [,atol]],f [,jac] [,w,iw])
[y,rd,w,iw]=ode("root",y0,t0,t [,rtol [,atol]],f [,jac],ng,g [,w,iw])
y=ode("discrete",y0,k0,kvect,f)

PARAMETERS

y0 : real vector or matrix (initial conditions).

t0 : real scalar (initial time).

t : real vector (times at which the solution is computed).

f : external (function or character string or list).

type : one of the following character string: "adams" "stiff" "rk"


"rkf" "fix" "discrete" "roots"

rtol,atol : real constants or real vectors of the same size as y.

jac : external (function or character string or list).

w,iw : real vectors.

ng : integer.

g : external (function or character string or list).

k0 : integer (initial time). kvect : integer vector.

DESCRIPTION
ode is the standard function for solving explicit ODE systems defined by:

dy/dt=f(t,y) , y(t0)=y0.

It is an interface to various solvers, in particular to ODEPACK. The type


of problem solved and the method used depend on the value of the first
optional argument type which can be one of the following strings:

<not given>: lsoda solver of package ODEPACK is called by default. It auto-


matically selects between nonstiff predictor-corrector Adams
method and stiff Backward Differentiation Formula (BDF)
method. It uses nonstiff method initially and dynamically mon-
itors data in order to decide which method to use.

"adams": This is for nonstiff problems. lsode solver of package ODEPACK is


called and it uses the Adams method.
"stiff": This is for stiff problems. lsode solver of package ODEPACK is
called and it uses the BDF method.

"rk": Adaptive Runge-Kutta of order 4 (RK4) method.

"rkf": The Shampine and Watts program based on Fehlberg's Runge-Kutta pair
of order 4 and 5 (RKF45) method is used. This is for non-stiff and
mildly stiff problems when derivative evaluations are inexpensive.
This method should generally not be used when the user is demanding
high accuracy.

"fix": Same solver as "rkf", but the user interface is very simple, i.e.
only rtol and atol parameters can be passed to the solver. This is
the simplest method to try.

"root": ODE solver with rootfinding capabilities. The lsodar solver of


package ODEPACK is used. It is a variant of the lsoda solver where
it finds the roots of a given vector function. See help on
ode_root for more details.

"discrete": Discrete time simulation. See help on ode_discrete for more


details.
In this help we only describe the use of ode for standard explicit ODE sys-
tems.

The simplest call of ode is: y=ode(y0,t0,t,f) where y0 is the vector of


initial conditions, t0 is the initial time, t is the vector of times at
which the solution y is computed and y is the solution vector
y=[y(t(1)),y(t(2)),...].

The input f to ode is an external i.e. a function with specified syntax, or


the name of a Fortran subroutine or a C function (character string) with
specified calling sequence or a list.

If f is a function, its syntax must be as follows:


ydot = f(t,y)
where t is a real scalar (time) and y a real vector (state). This function
is the RHS of the differential equation dy/dt=f(t,y).

If f is a character string, it refers to the name of a Fortran subroutine


or a C function, i.e. if ode(y0,t0,t,"fex") is the command, then the sub-
routine fex is called. This routine must have the following calling
sequence: f(n,t,y,ydot). It can be dynamically linked to Scilab by the link
function. Examples of such programs can be seen in the files SCIDIR/rou-
tines/default/README and SCIDIR/routines/default/Ex-ode.f.

The f argument can also be a list: if ode(y0,t0,t,lst) is the command, then


lst must be a list with the following structure:
lst=list(f,u1,u2,...un)
where f is a function with syntax:
ydot = f(t,y,u1,u2,...,un)
this allows to use parameters as the arguments of f.

The function f can return a p x q matrix instead of a vector. With this


matrix notation, we solve the n=p+q ODE's system dY/dt=F(t,Y) where Y is a
p x q matrix. Then initial conditions, Y0, must also be a p x q matrix and
the result of ode is the p x q(T+1) matrix [Y(t_0),Y(t_1),...,Y(t_T)].

Optional parameters can be given for the error of the solution: rtol and
atol are threshold for relative and absolute estimated errors. The esti-
mated error on y(i) is:
rtol(i)*abs(y(i))+atol(i)
and integration is carried out as far as this error is small for all compo-
nents of the state. If rtol and/or atol is a constant rtol(i) and/or
atol(i) are set to this constant value. Default values for rtol and atol
are respectively rtol=1.d-5 and atol=1.d-7 for most solvers and rtol=1.d-3

and atol=1.d-4 for "rfk" and "fix".

For stiff problems, it is better to give the Jacobian of the RHS function
as the optional argument jac. It is an external i.e. a function with
specified syntax, or the name of a Fortran subroutine or a C function
(character string) with specified calling sequence or a list.

If jac is a function the syntax should be as follows:


J=jac(t,y)
where t is a real scalar (time) and y a real vector (state). The result
matrix J must evaluate to df/dx i.e. J(k,i) = dfk /dxi with fk = kth com-
ponent of f.

If jac is a character string it refers to the name of a Fortran subroutine


or a C function, with the following calling sequence:
jac(n,t,y,ml,mu,J,nrpd). In most cases you have not to refer ml, mu and
nrpd (see source code in SCIDIR/routines/default/Ex-ode.f for an example).

If jac is a list the same conventions as for f apply.

Optional arguments w and iw are vectors for storing information returned


by the integration routine. When these vectors are provided in RHS of ode
the integration re-starts with the same parameters as in its previous
stop.

More options can be given to ODEPACK solvers by using %ODEOPTIONS variable.


See odeoptions help.

Ejemplo 3.9

// Simple one dimension ODE


// dy/dt=y^2-y sin(t)+cos(t), y(0)=0
deff("[ydot]=f(t,y)","ydot=y^2-y*sin(t)+cos(t)")
y0=0;t0=0;t=0:0.1:%pi;
y=ode(y0,t0,t,f)
plot(t,y)
// Simulation of dx/dt = A x(t) + B u(t) with u(t)=sin(omega*t),
// x0=[1;0]
// solution x(t) desired at t=0.1, 0.2, 0.5 ,1.
// A and u function are passed to RHS function in a list.
// B and omega are passed as global variables
deff("[xdot]=linear(t,x,A,u)","xdot=A*x+B*u(t)")
deff("[ut]=u(t)","ut=sin(omega*t)")
A=[1 1;0 2];B=[1;1];omega=5;
ode([1;0],0,[0.1,0.2,0.5,1],list(linear,A,u))
//
// Matrix notation
// Integration of the Riccati differential equation
// Xdot=A'*X + X*A - X'*B*X + C , X(0)=Identity
// Solution at t=[1,2]
deff("[Xdot]=ric(t,X)","Xdot=A''*X+X*A-X''*B*X+C")
A=[1,1;0,2]; B=[1,0;0,1]; C=[1,0;0,1];
t0=0;t=0:0.1:%pi;
X=ode(eye(A),0,t,ric)
//
// Computation of exp(A)
A=[1,1;0,2];
deff("[xdot]=f(t,x)","xdot=A*x");
ode(eye(A),0,1,f)
ode("adams",eye(A),0,1,f)
// with stiff matrix, Jacobian given
A=[10,0;0,-1];
deff("[xdot]=f(t,x)","xdot=A*x");
deff("[J]=Jacobian(t,y)","J=A")
ode("stiff",[0;1],0,1,f,Jacobian)

NOTA : Veanse también las ayudas de : ode_discrete, ode_root, dassl, impl, odedc, odeoptions,
csim, ltitr, rtitr

ESCRIBIENDO FUNCIONES

Definición de funciones en linea

-->deff('[x]=fact(n)','if n=0 then x=1,else x=n*fact(n-1),end')


Warning: obsolete use of = instead of ==
if n=0 then x=1,else x=n*fact(n-1),end
!
at line 2 of function fact called by :
deff('[x]=fact(n)','if n=0 then x=1,else x=n*fact(n-1),end')

-->10+fact(5)
ans =

130.
Escribiendo funciones fuera de linea

pendiente

También podría gustarte