Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Manual Sci Lab
Manual Sci Lab
FACULTAD DE INGENIERIA
POR
GICI
SANTIAGO DE CALI
" 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.
• 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 .
1
Tomado de http://www.inria.fr/Colloques/ALAPEDESSCILAB-eng.html
2. ESTRUCTURA DEL PROGRAMA
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
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
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).
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 :
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
apropos
CAPITULO II.2 COMANDOS BASICOS
- APRENDIENDO A TRAVÉS DE EJEMPLOS -
1. TIPOS DE DATOS
--> 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. !
--> 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
-->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 =
( 4, 10) sparse matrix
( 1, 2) 1.
( 3, 10) 3.
( 4, 5) 2.
ans =
( 1, 1) sparse matrix
( 1, 1) T
2.3 Listas
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 !
- 3.
Lt(1)
Lt(2)
blue
Lt(3)
! 0. 1. !
Lt(4)
10.
blue
10.
3. OPERACIONES
• Suma simple
-->a=1;
-->A=2;
-->a+A
ans=
3.
-->a=2; b=3;
-->a/b
ans=
0.6666667
-->b/a
ans=
1.5
• Matriz Inversa
-->inv(A)
ans =
! 0.5 0. 0. !
! 0. 0.3333333 0. !
! 0. 0. 0.25 !
! 1 4 7!
! 2 5 8!
! 3 6 9!
! 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. !
! 1. 2. 3. 4. 5. !
! 5. !
! 10. !
! 15. !
! 20. !
! 25. !
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 !
parte real
2
1 + 3z + 4.5z
parte imaginaria
4.5
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’
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.
graphics(2)
Scilab Function graphics(2)
NAME
2D PLOTTING
3D PLOTTING
RECTANGLE PLOTTING
ARC PLOTTING
ARROW PLOTTING
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
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)
COLORS
GRAPHICS CONTEXT
GRAPHICS PRIMITIVES
MOUSE POSITION
INTERACTIVE EDITOR
plot(x,y,[xcap,ycap,caption])
plot(y)
PARAMETERS
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>.
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
SEE ALSO
plot2d
AUTHOR
J.Ph.C.
FIGURA 2. Graficación de sin(x), donde x=0:0.1:2*%pi;
• Graficación en 3D
Pendiente
CAPITULO III. COMANDOS PARA SIMULACION EN CONTROL .
- APRENDIENDO A TRAVÉS DE EJEMPLOS -
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.
sA2
G ¢s £=
s ¢ sA3£ ,
--> 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”.
zA0.1153
G ¢ z £=1.7788
¢ zB1£ ¢ zB0.1089£ ,
1- z=poly(0,'z' ) ó
2- z=%z
finalmente debe formar un sistema lineal con la función escrita para que el scilab la interprete
--> Gzl=syslin('d',Gz )
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:
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
N, D : polynomial matrices
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)
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)
CALLING SEQUENCE
sl=tf2ss(h [,tol])
PARAMETERS
h : rational matrix
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))
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:
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)
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 :
CALLING SEQUENCE
[y [,x]]=csim(u,t,sl,[x0])
PARAMETERS
sl : list (syslin)
y : a matrix such that y=[y(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.
1. a function : [inputs]=u(t)
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'])
CALLING SEQUENCE
y=dsimul(sl,u)
PARAMETERS
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
-->sl=syslin('c',1/(s*s+0.2*s+1))
sl =
1
---------------
2
1 + 0.2s + s
-->instants=0:0.05:20;
-->y=csim('step',instants,sl);
-->xbasc();plot2d(instants',y')
-->// Delayed step response
-->y1=csim(u,instants,sl);plot2d(instants',y1');
-->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);
-->u=ones(instants);
Warning :redefining function: u
-->yyy=flts(u,sld);
-->xbasc();plot(instants,yyy)
-->u=0*ones(instants);u(1)=1/dt;
-->yy=flts(u,sld);
-->xbasc();plot(instants,yy)
-->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 !
-->z=poly(0,'z');
! 1+z 1+z !
! ----- ----------- !
! 1-z 2 !
! !
! 2 2!
! 1 + 2z + z 1 + 2z + z !
!----------------- ---------------- !
! 2!
! 2 - 2z 9 + 6z + z !
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
ng : integer.
DESCRIPTION
ode is the standard function for solving explicit ODE systems defined by:
dy/dt=f(t,y) , y(t0)=y0.
"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.
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
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.
Ejemplo 3.9
NOTA : Veanse también las ayudas de : ode_discrete, ode_root, dassl, impl, odedc, odeoptions,
csim, ltitr, rtitr
ESCRIBIENDO FUNCIONES
-->10+fact(5)
ans =
130.
Escribiendo funciones fuera de linea
pendiente