Você está na página 1de 77

SISTEMAS AUTOMTICOS DE CONTROL INTRODUCCIN AL MANEJO DE MATLAB Y SCILAB

Santiago de Cali Universidad del Valle Facultad de Ingeniera Escuela de Ingeniera Elctrica y Electrnica 2010
1

MATLAB MATLAB (abreviatura de MATrix LABoratory, "laboratorio de matrices") es un software matemtico que ofrece un entorno de desarrollo integrado (IDE) con un lenguaje de programacin propio (lenguaje M). Est disponible para las plataformas Unix, Windows y Apple Mac OS X. Entre sus prestaciones bsicas se hallan: la manipulacin de matrices, la representacin de datos y funciones, la implementacin de algoritmos, la creacin de interfaces de usuario (GUI) y la comunicacin con programas en otros lenguajes y con otros dispositivos hardware. El paquete MATLAB dispone de dos herramientas adicionales que expanden sus prestaciones, a saber, Simulink (plataforma de simulacin multidominio) y GUIDE (editor de interfaces de usuario - GUI). Adems, se pueden ampliar las capacidades de MATLAB con las cajas de herramientas (toolboxes); y las de Simulink con los paquetes de bloques (blocksets). Es un software muy usado en universidades y centros de investigacin y desarrollo. En los ltimos aos ha aumentado el nmero de prestaciones, como la de programar directamente procesadores digitales de seal o crear cdigo VHDL. VENTANA INICIAL

Figura 1. Ventana Inicial Matlab. Command Window, la sub-ventana que aparece en la parte derecha es donde se ejecutan los comandos de MATLAB, en la pantalla mostrada en la figura 1 se observan instrucciones introducidas en el espacio de trabajo. En la parte superior izquierda de la pantalla aparecen dos ventanas: en la parte superior aparece la ventana Current Directory que muestra los ficheros del directorio activo o actual y se puede alternar con Workspace haciendo clic en la pestaa correspondiente. El Workspace contiene informacin sobre todas las variables que se hayan definido en esta sesin. La ventana inferior izquierda es 2

Command History y muestra los ltimos comandos ejecutados en la Command Window. Estos comandos se pueden volver a ejecutar haciendo doble clic sobre ellos. Haciendo clic sobre un comando con el botn derecho del ratn se muestra un men contextual con las posibilidades disponibles en ese momento. Para editar uno de estos comandos hay que copiarlo antes al Command Window.

GENERALIDADES Los clculos que no se asignan a una variable en concreto se asignan a la variable de respuesta por defecto que es ans (del ingls, answer): >>2+3 ans = 5 Sin embargo, si el clculo se asigna a una variable, el resultado queda guardado en ella: >>x=2+3 x= 5 Para conocer el valor de una variable, basta teclear su nombre: >>x x= 5 Si se aade un punto y coma (;) al final de la instruccin, la mquina no muestra la respuesta... >>y=5*4; ... pero no por ello deja de realizarse el clculo. >>y y= 20 Las operaciones se evalan por orden de prioridad: primero las potencias, despus las multiplicaciones y divisiones y, finalmente, las sumas y restas. Las operaciones de igual prioridad se evalan de izquierda a derecha: >>2/4*3 ans = 1.5000 >>2/(4*3) ans = 0.1667 Se pueden utilizar las funciones matemticas habituales. As, por ejemplo, la funcin coseno, >>cos(pi) %pi es una variable con valor predeterminado 3.14159... ans = -1 o la funcin exponencial >>exp(1) %Funcin exponencial evaluada en 1, es decir, el nmero e 3

ans = 2.7183 Adems de la variable pi, MATLAB tiene otras variables con valor predeterminado; ste se pierde si se les asigna otro valor distinto. Por ejemplo: >>eps %psilon de la mquina. Obsrvese que MATLAB trabaja en doble precisin ans = 2.2204e-016 pero... >>eps=7 eps = 7 Otro ejemplo de funcin matemtica: la raz cuadrada; como puede verse, trabajar con complejos no da ningn tipo de problema. La unidad imaginaria se representa en MATLAB como i o j, variables con dicho valor como predeterminado: >>sqrt(-4) ans = 0+ 2.0000i El usuario puede controlar el nmero de decimales con que aparece en pantalla el valor de las variables, sin olvidar que ello no est relacionado con la precisin con la que se hacen los clculos, sino con el aspecto con que stos se muestran: >>1/3 ans = 0.3333 >>format long >>1/3 ans = 0.33333333333333 >>format %Vuelve al formato estndar que es el de 4 cifras decimales

Para conocer las variables que se han usado hasta el momento: >>who Your variables are: ans eps x y o, si se quiere ms informacin (obsrvese que todas las variables son arrays): >>whos Name Size Bytes ans 1x1 8 eps 1x1 8 x 1x1 8 y 1x1 8

Class Attributes double array double array double array double array 4

Grand total is 4 elements using 32 bytes Para deshacerse de una variable >>clear y >>who Your variables are: ans eps x VECTORES Y MATRICES Para definir un vector fila, basta introducir sus coordenadas entre corchetes: >>v=[1 2 3] %Vector de 3 coordenadas v= 1 2 3 >>w=[4 5 6]; El operador ' es el de trasposicin (en realidad trasposicin y conjugacin): >>w' ans = 4 5 6 Si queremos declarar un vector de coordenadas equiespaciadas entre dos dadas, por ejemplo, que la primera valga 0, la ltima 20 y la distancia entre coordenadas sea 2, basta poner: >>vect1=0:2:20 vect1 = 0 2 4 6 8 10 12 14 16 18 20 Equivalentemente, si lo que conocemos del vector es que la primera coordenada vale 0, la ltima 20 y que tiene 11 en total, escribiremos: >>vect2=linspace(0,20,11) vect2 = 0 2 4 6 8 10 12 14 16 18 20 A las coordenadas de un vector se accede sin ms que escribir el nombre del vector y, entre parntesis, su ndice: >>vect2(3) ans = 4 y se pueden extraer subvectores, por ejemplo: >>vect2(2:5) ans= 2 4 6 8 o, >>vect1(:) 5

ans= 0 2 4 6 8 10 12 14 16 18 20 Las matrices se escriben como los vectores, pero separando las filas mediante un punto y coma; as una matriz 3x3: >>M=[1 2 3;4 5 6;7 8 9] M= 1 2 3 4 5 6 7 8 9 >>M' ans = %Su traspuesta (su adjunta) 1 4 7 2 5 8 3 6 9 >>mat=[v;w;0 0 1] mat = 1 2 3 4 5 6 0 0 1 %Tambin es una matriz 3x3

A los elementos de una matriz se accede sin ms que escribir el nombre de la matriz y, entre parntesis, los respectivos ndices: >>mat(1,3) %Elemento en la primera fila y tercera columna de la matriz mat ans = 3 Tambin se puede acceder a una fila o columna completas, >>mat(:,2) %Segunda columna de mat ans = 2 5 0 >>mat(2,:) %Su segunda fila 6

ans = 4 5 6 acceder a la matriz como si fuera una columna, >>M(2:7) %Los elementos segundo a sptimo de la matriz como fila ans = 4 7 2 5 8 3 o acceder a cualquiera de sus submatrices >>mat(2:3,[1 3]) %Submatriz formada por los elementos que estn en %"todas" las filas que hay entre la segunda y la tercera y %en las columnas primera y tercera ans = 4 6 0 1 Existen algunas matrices definidas previamente; por ejemplo, la matriz identidad, >>eye(5) %eye se pronuncia en ingls como I ans = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 la matriz nula, >>zeros(3) ans = 0 0 0 0 0 0 0 0 0 o la matriz cuyos elementos valen todos 1: >>ones(4) ans = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Se puede conocer el tamao de una matriz y la longitud de un vector: >>size(mat) %Dimensiones de la matriz mat (nmero de filas y de columnas) ans = 3 3 >>size(v) ans = 1 3 7

>>length(v) %Longitud del vector (nmero de coordenadas) ans = 3 Existen comandos que permiten crear de forma sencilla matrices. Por ejemplo: >>diag(v) %Matriz diagonal cuya diagonal es el vector v ans = 1 0 0 0 2 0 0 0 3 >>diag(diag(M)) %Matriz diagonal con la diagonal de M. La sentencia diag(M) da %el vector formado por la diagonal de la matriz M ans = 1 0 0 0 5 0 0 0 9 >>diag(ones(1,4),1)+diag(ones(1,4),-1) %Matriz tridiagonal 5x5 con 0 en la diagonal %principal y 1 en la sub y superdiagonal ans = 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 >>tril(M) %Matriz formada por la parte triangular inferior de M. ans = 1 0 0 4 5 0 7 8 9 >>triu(M) %Matriz formada por la parte triangular superior de M. ans = 1 2 3 0 5 6 0 0 9 OPERACIONES CON VECTORES Y MATRICES Las funciones matemticas elementales estn definidas de forma que se pueden aplicar sobre arrays. El resultado es el array formado por la aplicacin de la funcin a cada elemento del array. As: >>log(v) ans = 0 0.6931 1.0986 >>p=(0:0.1:1)*pi %Vector definido como el producto de un vector por un escalar p= 8

0 0.3142 0.6283 0.9425 1.2566 1.5708 1.8850 2.1991 2.5133 2.8274 3.1416 >>x=sin(p) x= 0 0.3090 0.5878 0.8090 0.9511 1.0000 0.9511 0.8090 0.5878 0.3090 0.0000 Las operaciones habituales entre arrays (suma, resta y producto escalar de vectores; suma, resta, producto y potencia de matrices) se representan con los operadores habituales: >>v,w %Recordamos los valores de v y w v= 1 2 3 w= 4 5 6 >>z=v*w' %Producto escalar (producto de matrices 1x3 por 3x1) z= 32 >>Z=w'*v %Producto de matrices 3x1 por 1x3 = Matriz 3x3 Z= 4 8 12 5 10 15 6 12 18 >>v*w % Los vectores v y w no se pueden multiplicar ??? Error using ==> mtimes Inner matrix dimensions must agree. >>mat mat = %Recordamos el valor de la matriz mat 1 2 3 4 5 6 0 0 1 >>mat^2 ans = 9 24 0 %Matriz mat elevada al cuadrado 12 18 33 48 0 1

Tambin pueden efectuarse multiplicaciones, divisiones y potencias de arrays, entendindolas como elemento a elemento (como, de hecho, se realizan la suma y la resta). El operador utilizado para ellas es el habitual precedido por un punto; es decir: >>v.*w %Vector formado por los productos de las respectivas coordenadas: %ans(i)=v(i)*w(i) ans = 4 10 18 9

>>w./v %Vector formado por el cociente de cada coordenada de w entre la %coordenada correspondiente de v: ans(i)=w(i)/v(i) ans = 4.0000 2.5000 2.0000 >>mat.^2 %Matriz cuyos elementos son los de mat elevados %al cuadrado: ans(i,j)=mat(i,j)^2 ans = 1 4 9 16 25 36 0 0 1 Finalmente, pueden calcularse determinantes: >>det(mat) ans = -3 y resolverse sistemas de ecuaciones lineales con el verstil comando \: >>mat\v' ans = 2.6667 -5.3333 3.000 VARIABLES LGICAS Tambin existen variables lgicas que toman los valores 0 (falso) o 1 (verdadero). Por ejemplo: >>abs(v)>=2 %Vector lgico cuyas coordenadas valen 1 si la coordenada %correspondiente de v es >= 2 y 0 si no lo es ans = 0 1 1 >>vector=v(abs(v)>=2) %Vector formado por las coordenadas de v que %verifican la desigualdad vector = 2 3 >>v2=[3 2 1] v2 = 3 2 1 >>logica=v==v2 %Asignacin de un valor lgico (el doble signo igual es el %igual lgico) logica = 0 1 0 >>logic2=v~=v2 %Distinto (~ es el operador de negacin) logic2 = 1 0 1 10

POLINOMIOS Se puede trabajar con polinomios: basta tener en cuenta que un polinomio no es ms que un vector. El orden de los coeficientes es de mayor a menor grado, por ejemplo: >>p=[1 0 2 0 3] %Polinomio x^4+2*x^2+3 p= 1 0 2 0 3 >>q=[2 1 0] q= 2 1 0 %Polinomio 2*x^2+x

MATLAB tiene funciones especficas para polinomios como: >>polyval(p,-1) %Evaluacin del polinomio x^4+2x^2+3 en x=-1 ans = 6 >>pro=conv(p,q) %Producto de los polinomios p y q pro = 2 1 4 2 6 3 0 >>deconv(pro,p) %Cociente entre pro y p; obviamente el resultado es q ans = 2 1 0 >>roots(pro) %Races del polinomio pro ans = 0 0.6050+1.1688i 0.6050-1.1688i -0.6050+1.1688i -0.6050-1.1688i -0.5000 >>poly([i -i 1/2 pi]) %Polinomio mnico que tiene por races a los %nmeros i, -i, 0.5 y pi ans = 1.0000 -3.6416 2.5708 -3.6416 1.5708 DERIVADAS Y PRIMITIVAS Dentro del mdulo (toolbox) de matemtica simblica, se utiliza el programa de clculo simblico MAPLE. Con estas herramientas, se puede trabajar con funciones, >>f='sin(x)' %Funcin sin(x) definida mediante una cadena de caracteres f= sin(x) calcular derivadas, >>diff(f) ans = 11

cos(x) >>diff(f,2) %Derivada segunda de f ans = -sin(x) o encontrar primitivas. >>int('log(x)') %Primitiva de la funcin logaritmo ans = x*log(x)-x >>diff('x*log(x)-x') %Comprobacin ans = log(x) GRFICAS DE FUNCIONES MATLAB tiene un gran potencial de herramientas grficas. Se pueden dibujar los valores de un vector frente a otro (de la misma longitud): >>x=pi*(-1:0.1:1); >>y=x.*sin(x); >>plot(x,y) %Por defecto une los puntos (x(i),y(i)) mediante una poligonal
1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0

0.5

1.5

2.5

3.5

Figura 2. Grfico xsin(x) Como se ve, con pocos puntos la grfica tiene un aspecto demasiado lineal a trozos. Para "engaar" al ojo, basta tomar ms puntos. 12

>>x=pi*(-1:0.01:1); >>y=x.*sin(x); >>plot(x,y)


2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0 -4

-3

-2

-1

Figura 3. Grfica xsin(x) ms definida. Tambin pueden dibujarse funciones. As: >>fplot('sin(x)',[0 2*pi]) %Dibuja la funcin seno en el intervalo [0,2*pi]
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1

Figura 4. Grfico con la funcin fplot. 13

>>hold on

%Mantiene en la ventana grfica los dibujos anteriores

>>fplot('cos(x)',[0 2*pi]) %Dibuja sobre la grfica anterior la funcin cos(x)


1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1

Figura 5. Grfico de sinx y cosx. >>hold off %Con esto olvida los dibujos anteriores %y dibuja en una ventana nueva

>>fplot('x^2*sin(1/x)',[-0.05 0.05]) %Dibuja la funcin x^2*sin(1/x)


2.5 2 1.5 1 0.5 0 -0.5 -1 -1.5 -2 -2.5 -0.05 x 10
-3

-0.04

-0.03

-0.02

-0.01

0.01

0.02

0.03

0.04

0.05

Figura 6. Otro grfico de una funcin. 14

Tambin puede usarse el verstil comando ezplot (se lee como easy plot) que permite dibujar funciones, >>ezplot('exp(x)') %Dibuja la funcin exponencial en un intervalo adecuado a la funcin
exp(x) 250

200

150

100

50

0 -4 -3 -2 -1 0 x 1 2 3 4 5 6

Figura 7. Grfico de una funcin exponencial. curvas en paramtricas, >>ezplot('sin(t)','cos(t)',[0 pi])


x = sin(t), y = cos(t) 1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1

-0.5

0.5 x

1.5

Figura 8. Grfico de una funcin paramtrica. 15

e implcitas >>ezplot('x^2 - y^2 - 1')


x 2-y 2-1 = 0 6

-2

-4

-6 -6 -4 -2 0 x 2 4 6

Figura 9. Grfico de una funcin implcita. Tambin permite dibujar superficies. La forma ms sencilla es mediante el comando ezsurf, >>ezsurf('sin(x*y)',[-2 2 -2 2])
sin(x y)

0.5

-0.5

-1 2 1 0 -1 y -2 -2 -1 x 1 0 2

Figura 10. Grfico de una superficie. 16

aunque se pueden realizar grficas ms sofisticadas: >>t=0:0.001:0.009; >>v=900:1025; >>[T V]=meshgrid(t,v); >>aux1=16*pi^2*(T.^2).*((V-918).^2).*((V-1011).^2); >>aux2=aux1+(2*V-1929).^2; >>w=T./aux2; >>z=35000000*w; >>surfl(t,v,z); %Este comando dibuja la superficie creada mediante las >>shading interp; %ordenes anteriores. Los siguientes sirven para modificar >>colormap(pink); %el dibujo obtenido >>rotate3d; %Sirve para girar la figura mediante el ratn
java.lang.NullPointerException at com.mathworks.jmi.bean.MatlabBeanInterface.addCallback(MatlabBeanInterface.java:680) at com.mathworks.jmi.bean.MatlabCallbackInterface.addCallback(MatlabCallbackInterface.java:128)

50 40 30 20 10 0 1050 1000 950 900 0.002 0 0.006 0.004 0.01 0.008

Figura 11. Otra superficie. PROGRAMACIN Para escribir un programa con MATLAB habr que crear un fichero que tenga extensin .m y contenga las instrucciones. Esto se puede hacer con cualquier editor de textos, pero tiene algunas ventajas usar el editor propio de MATLAB llamado medit. MATLAB trabaja con memoria dinmica, por lo que no es necesario declarar las variables que se van a usar. Por esta misma razn, habr que tener especial cuidado y cerciorarse de que entre las variables del espacio de trabajo no hay ninguna que se llame igual que las de nuestro programa (proveniente, por ejemplo, de un programa previamente ejecutado en la misma sesin), porque esto podra provocar 17

conflictos. A menudo, es conveniente reservar memoria para las variables (por ejemplo, si se van a utilizar matrices muy grandes); para ello, basta con asignarles cualquier valor. Del mismo modo, si se est usando mucha memoria, puede ser conveniente liberar parte de ella borrando (clear) variables que no se vayan a usar ms. Un programa escrito en MATLAB admite la mayora de las estructuras de programacin al uso y su sintaxis es bastante estndar. En los siguientes ejemplos se muestra la sintaxis de algunas de estas estructuras (if, for, while,...). Programa 1: Calcular la suma de los n primeros trminos de la sucesin 1, 2x, 3x^2, 4x^3, ...
n=input('Cuntos trminos quieres sumar? '); x=input('Dame el valor del numero x '); suma=1; for i=2:n suma=suma+i*x^(i-1); end disp('El valor pedido es') disp(suma)

Programa 2: Decidir si un nmero natural es primo.


n=input('Nmero natural que deseas saber si es primo '); i=2; primo=1; while i<=sqrt(n) if rem(n,i)==0 % Resto de dividir n entre i primo=0; break end i=i+1; end if primo disp('El nmero dado es primo.') else disp('El nmero dado no es primo.') disp('De hecho, es divisible por:') disp(i) end

Programa 3: Escribir un nmero natural en una base dada (menor que diez).
n=input('Dame el nmero que quieres cambiar de base '); base=input('En qu base quieres expresarlo? '); i=1; while n>0 c(i)=rem(n,base); n=fix(n/base); % Parte entera de n/base i=i+1; end disp('La expresin en la base dada es:') i=i-1; disp(c(i:-1:1))

Por ltimo, tambin pueden programarse funciones. La primera instruccin de un fichero que contenga una funcin de nombre fun debe ser: function [argumentos de salida]=fun(argumentos de entrada) 18

Es conveniente que el fichero que contenga la funcin se llame como ella; as, la funcin anterior debera guardarse en el fichero fun.m; por ejemplo, si se desea programar una funcin que calcule, mediante el algoritmo de Euclides, el mximo comn divisor de dos nmeros naturales, basta escribir un fichero euclides.m cuyo contenido sea:
function m=euclides(a,b) % Clculo del mximo comn divisor de dos nmeros naturales % mediante el algoritmo de Euclides if a<b c=b; b=a; a=c; end while b>0 c=rem(a,b); a=b; b=c; end m=a;

Si, una vez escrito el fichero anterior, en el espacio de trabajo o en un programa se escribe la instruccin >>mcd=euclides(33,121) en la variable mcd se almacenar el valor 11. Las variables de una funcin son siempre locales. Por tanto, aunque en el seno de la funcin se modifiquen los argumentos de entrada, el valor de las variables correspondientes queda inalterado. Por ejemplo, en la funcin euclides.m se modifica el valor de los argumentos de entrada, pero, sin embargo: >>x=15; >>mcd=euclides(x,3); >>x x= 15 Si se pretende que las modificaciones de un argumento de entrada afecten a la variable correspondiente, deber situarse dicho argumento, adems, en la lista de argumentos de salida. DESARROLLO EN FRACCIONES SIMPLES MATLAB tiene una orden para obtener el desarrollo en fracciones simples de B(s)/A(s). En primer lugar se presentar el enfoque de MATLAB para detener el desarrollo en fracciones simples de B(s)/A(s). Despus se analiza el procedimiento que sigue MATLAB para obtener los ceros y los polos de B(s)/A(s). Considrese la funcin de transferencia B(s)/A(s): () 0 + 1 1 + + = = () + 1 1 + + Donde algunos a i y b i pueden ser cero. En MATLAB, los vectores fila num y den especifican los coeficientes del numerador y del denominador en la funcin de transferencia. Es decir, = [0 1 ] = [1 1 ] 19

El comando

[, , ] = (, ) encuentra los residuos (r), los polos (p) y los trminos directos (k) de un desarrollo en fracciones simples del cociente de dos polinomios B(s) y A(s). El desarrollo en fracciones simples de B(s)/A(s) se obtiene mediante () (1) (2) () = + ++ + () () () (1) (2)

Ejemplo. Considere la siguiente funcin de transferencia: () 2 3 + 5 2 + 3 + 6 = () 3 + 6 2 + 11 + 6 Para esta funcin, = [2 5 3 6] = [1 6 11 6] La orden [, , ] = (, ) Proporciona el resultado siguiente: >> num=[2 5 3 6]; >> den=[1 6 11 6]; >> [r,p,k]=residue(num,den) r= -6.0000 -4.0000 3.0000 p= -3.0000 -2.0000 -1.0000 k= 2

(Observe que los residuos se devuelven en el vector columna r, las posiciones de los polos en el vector columna p y el trmino directo en el vector fila k). sta es la representacin en MATLAB del siguiente desarrollo en fracciones simples de B(s)/A(s): () 2 3 + 5 2 + 3 + 6 = () 3 + 6 2 + 11 + 6 6 4 3 = + + +2 + 3 + 2 + 1 La funcin residue tambin se puede utilizar para obtener los polinomios (numerador y denominador) a partir de su desarrollo en fracciones simples. Esto es, el comando [, ] = (, , ) donde r, p y k estn como se obtienen en el resultado de MATLAB anterior, convierte el desarrollo en fracciones simples en la razn de polinomios B(s)/A(s) del modo siguiente: >> [num,den]=residue(r,p,k); >> printsys(num,den,'s')

20

num/den = 2 s^3 + 5 s^2 + 3 s + 6 ----------------------s^3 + 6 s^2 + 11 s + 6 (, , ) imprime num/den en trminos del cociente de los polinomios en s. La funcin

Ejemplo. Obtenga el desarrollo B(s)/A(s) siguiente en fracciones simples utilizando MATLAB. 2 + 2 + 3 () 2 + 2 + 3 = = 3 ( + 1)3 () + 3 2 + 3 + 1 Para esta funcin, se tiene = [0 1 2 3] = [1 3 3 1] La orden [, , ] = (, ) Proporciona el resultado que se muestra a continuacin. Es la representacin en MATLAB del desarrollo en fracciones simples de B(s)/A(s): () 1 0 2 = + + () + 1 ( + 1)2 ( + 1)3 >> num=[0 1 2 3] num = 0 1 2 3 >> den=[1 3 3 1] den = 1 3 3 1 >> [r,p,k]=residue(num,den) r= 1.0000 0.0000 2.0000 p= -1.0000 -1.0000 -1.0000 k= [] Observe que el trmino directo k es cero. Para obtener la funcin original B(s)/A(s) a partir de r, p, y k se introducen las siguientes lneas: [, ] = (, , ); (, , ) Entonces se mostrar el num/den siguiente: >> [num,den]=residue(r,p,k); >> printsys(num,den,'s') 21

num/den = s^2 + 2 s + 3 --------------------s^3 + 3 s^2 + 3 s + 1 ENCONTRAR LOS CEROS Y LOS POLOS DE B(S)/A(S) CON MATLAB MATLAB tiene una funcin [, , ] = 2(, ) para obtener los ceros, polos y ganancia k de B(s)/A(s).

Considrese el sistema definido por 4 2 + 16 + 12 () = () 4 + 12 3 + 44 2 + 48 Para obtener los ceros (z), plos (p) y ganancia (k), e introduce el siguiente programa de MATLAB en el computador: >> num=[0 0 4 16 12]; >> den=[1 12 44 48 0]; >> [z,p,k]=tf2zp(num,den) z= -3 -1 p= 0 -6.0000 -4.0000 -2.0000 k= 4 Los ceros son -3 y -1. Los polos estn en s=0, -6, -4 y -2. La ganancia k es 4. Si los ceros, los polos y la ganancia k estn dados, entonces el siguiente programa en MATLAB generar num/den: >> z=[-1; -3]; >> p=[0; -2; -4; -6]; >> k=4 k= 4 >> [num,den]=zp2tf(z,p,k); >> printsys(num,den,'s') num/den = 4 s^2 + 16 s + 12 ---------------------------s^4 + 12 s^3 + 44 s^2 + 48 s 22

OBTENCIN DE FUNCIONES DE TRANSFERENCIA EN CASCADA, EN PARALELO Y REALIMENTADAS (EN LAZO CERRADO) UTILIZANDO MATLAB En el anlisis de sistemas de control, frecuentemente se necesita calcular funciones de transferencia en cascada, funciones de transferencia conectadas en paralelo y funciones de transferencia realimentadas (en lazo cerrado). MATLAB tiene funciones adecuadas para obtener las funciones de transferencia en cascada, paralelo y realimentada (lazo cerrado). Supngase que hay dos componentes G 1 (s) y G 2 (s) conectadas de diferentes formas como se muestra en la figura 1, donde 1 2 1 () = , 2 () = 1 2

Para obtener las funciones de transferencia del sistema en cascada, en paralelo o realimentado (lazo cerrado) se utilizan las siguientes instrucciones: [num, den] = series(num1, den1, num2, den2) [num, den] = parallel(num1, den1, num2, den2) [num, den] = feedback(num1, den1, num2, den2) Como ejemplo, se considera el caso en el que 10 1 = , 1 () = 2 + 2 + 10 1 2 () = 5 2 = + 5 2

El programa 4 en MATLAB calcula C(s)/R(s) = num/den para cada situacin de G 1 (s) y G 2 (s). Obsrvese que la instruccin printsys(num,den) muestra el num/den [esto es, la funcin C(s)/R(s)] del sistema considerado.

Figura 12. (a) Sistema en cascada; (b) sistema paralelo; (c) sistema realimentado (lazo cerrado). 23

Programa 4: >> num1 = [0 0 10]; >> den1=[1 2 10]; >> num2=[0 5]; >> den2=[1 5]; >> [num,den]=series(num1,den1,num2,den2); >> printsys(num,den) num/den = 50 ----------------------s^3 + 7 s^2 + 20 s + 50 >> [num,den]=parallel(num1,den1,num2,den2); >> printsys(num,den) num/den = 5 s^2 + 20 s + 100 ----------------------s^3 + 7 s^2 + 20 s + 50 >> [num,den]=feedback(num1,den1,num2,den2); >> printsys(num,den) num/den = 10 s + 50 -----------------------s^3 + 7 s^2 + 20 s + 100 ANLISIS DE LA RESPUESTA TRANSITORIA CON MATLAB El procedimiento prctico para dibujar las curvas de respuesta temporal de sistemas de orden mayor que segundo es mediante simulacin con computador. En esta seccin se presenta el enfoque computacional para el anlisis de la respuesta transitoria con MATLAB. En particular se discute la respuesta escaln, impulso, rampa y las respuestas a otras entradas simples. La funcin de transferencia de un sistema se representa mediante dos arrays de nmeros. Considrese el sistema () 2 + 25 = 2 () + 4 + 25 Este sistema se representa como dos arrays, cada uno de los cuales contiene los coeficientes de los polinomios en potencias decrecientes de s del modo siguiente: = [2 25] = [1 4 25] Una representacin alternativa es = [0 2 25] = [1 4 25] Si se conocen num y den (el numerador y denominador de la funcin de transferencia en lazo cerrado), instrucciones del tipo 24

(, ), (, , ) generarn grficas de respuestas escaln unitario. (En el comando step, t es el tiempo especificado por el usuario.). Obsrvese que el comando step (sys) se puede utilizar para obtener la respuesta escaln unitario de un sistema. Primero se define el sistema mediante = (, ) Entonces, para obtener, por ejemplo, la respuesta escaln unitario, se introduce () en el computador.

Cuando los comandos step tienen argumentos en el lado izquierdo, como en [, , ] = (, , ) no aparece una grfica en la pantalla. Por tanto, es necesario usar un comando plot para ver las curvas de respuesta. Las matrices y y x contienen la salida y la respuesta del estado del sistema, respectivamente, evaluadas en los puntos de tiempo de clculo t, (y tiene tantas columnas como salidas y una fila para cada elemento en t, x tiene tantas columnas como estados y una fila para cada elemento en t.) Escritura de texto en la pantalla de las grficas: Para escribir texto en la pantalla de las grficas, introduzca, por ejemplo, los enunciados siguientes: (3.4, 0.06, 1) y (3.4, 1.4, 2)

El primer enunciado le indica a la computadora que escriba Y1, empezando en las coordenadas x=3.4, y=-0.06. De modo similar, el segundo enunciado le indica a la computadora que escriba Y2, empezando en las coordenadas x = 3.4, y = 1.4. Otra forma de escribir un texto o textos en una grfica es utilizar el comando gtext. La sintaxis es ()

Cuando se ejecuta gtext, el computador espera hasta que el cursor se posiciona (utilizando el ratn) la pantalla en la posicin deseada. Cuando se pulsa el botn izquierdo del ratn, el texto encerrado en comillas simples se escribe en el dibujo en la posicin sealada por el cursor. Se puede utilizar cualquier nmero de comandos gtext en una grfica. Ejemplos: Se tiene la siguiente funcin de transferencia. () 25 = 2 () + 4 + 25 >>num=[0 0 25]; >> den=[1 4 25]; >> step(num,den) %Respuesta al escaln unitario >> title('Respuesta escaln unitario de G(s)=25/(s^2+4s+25)') >> grid

25

Respuesta escaln unitario de G(s)=25/(s 2+4s+25) 1.4

1.2

Amplitude

0.8

0.6

0.4

0.2

0.5

1.5 Time (sec)

2.5

Figura 13. Respuesta al escaln unitario. Para la funcin de transferencia: () 1 = 2 () + 0.2 + 1

>> num=[0 0 1]; >> den=[1 0.2 1]; >> impulse(num,den); %Respuesta al impulso unitario >> grid >> title('Respuesta impuso unitario de G(s)=1/(s^2+0.2s+1)')

Para tener respuesta a una entrada rampa unitaria, se puede proceder utilizando el comando STEP para tal fin. Si la funcin de transferencia a analizar es: () 1 = 2 () + + 1 Y la entrada R(s) es: 1 () = 2 Para la utilizacin del comando step, la funcin de transferencia original se multiplica por un integrador, de tal forma que: 1 1 () = 2 ( + + 1) Por lo tanto: >> num=[0 0 0 1]; >> den=[1 1 1 0]; 26

>> t=0:0.1:7; %Puntos de tiempo de clculo >> c=step(num,den,t); %Para etiquetar en forma distinta los ejes x y y >> %eje x->'tseg', eje y->'entrada y salida' >> %[y,x,t]=step(num,den,t) >> plot(t,c,'o',t,t,'-') >> grid >> title('Curva de respuesta rampa unitaria para el sistema G(s)=1/(s^2+s+1)') >> xlabel('tseg') >> ylabel('Entrada y Salida')

Respuesta impuso unitario de G(s)=1/(s 2+0.2s+1) 1 0.8 0.6 0.4

Amplitude

0.2 0 -0.2 -0.4 -0.6 -0.8

10

20

30 Time (sec)

40

50

60

Figura 14. Respuesta al Impulso Unitario. Descripcin en MATLAB de un sistema estndar de segundo orden: El sistema de segundo orden 2 () = 2 2 + 2 + se denomina sistema de segundo orden estndar. Dadas n y , el comando (, ) o (, , ) imprime num/den como un cociente de polinomios en s. Considrese, por ejemplo, el caso en el que estndar de segundo orden as: >> wn=5; >> damping_ratio=0.4; >> [num0,den]=ord2(wn,damping_ratio); >> num=5^2*num0;
n

= 5rad/seg y = 0.4. El programa genera el sistema

27

>> printsys(num,den,'s') num/den = 25 -------------s^2 + 4 s + 25


Curva de respuesta rampa unitaria para el sistema G(s)=1/(s 2+s+1) 7

Entrada y Salida

0 0

3 tseg

Figura 15. Respuesta Rampa Unitaria. Obtencin de la respuesta escaln unitario de un sistema dado como funcin de transferencia: Considere la respuesta escaln unitario del sistema dado por 25 () = 2 + 4 + 25

El programa produce la grfica de la respuesta escaln unitario de este sistema, as:


%----------Respuesta a un escaln unitario---------%*****Introduzca el numerador y el denominador de la funcin %de transferencia***** num=[0 0 25]; den=[1 4 25]; %*****Introduzca la siguiente orden de respuesta escaln***** step(num,den) %*****Introduzca grid y el ttulo de la grfica***** grid title('Respuesta a un escaln unitario de G(s)=25/(s^2+4s+25)')

28

Respuesta a un escaln unitario de G(s)=25/(s 2+4s+25) 1.4

1.2

Amplitude

0.8

0.6

0.4

0.2

0.5

1.5 Time (sec)

2.5

Figura 16. Respuesta al Escaln Unitario. Utilizando el comando pzmap, este nos permite visualizar el diagrama de polos y ceros. >> num=[1 11]; >> den=[1 5 6]; >> funtran=tf(num,den) Transfer function: s + 11 ------------s^2 + 5 s + 6 >> pzmap(funtran)
Pole-Zero Map 1 0.8 0.6 0.4

Imaginary Axis

0.2 0 -0.2 -0.4 -0.6 -0.8 -1 -12

-10

-8

-6 Real Axis

-4

-2

Figura 17. Mapa de Polos y Ceros. 29

LUGAR GEOMTRICO DE LAS RAICES La grfica del lugar geomtrico de las races de un sistema se obtiene con el comando rlocus. >> numc=[0 6 7]; >> denc=[12 9 13]; >> rlocus(numc,denc)
Root Locus 1.5

0.5

Imaginary Axis

-0.5

-1

-1.5 -5

-4

-3

-2 Real Axis

-1

Figura 18. Lugar Geomtrico de las Races. RESPUESTA EN FRECUENCIA Las trazas de bode se generan con el comando bode. >> bode(funtran)
Bode Diagram 20

Magnitude (dB) Phase (deg)

-20

-40

-60 0

-45

-90

-135 10
-1

10

10

10

10

Frequency (rad/sec)

Figura 19. Diagramas de Bode. 30

Tambin es posible obtener el margen de fase y ganancia directamente desde MATLAB con el comando margin. >> margin(funtran)

Bode Diagram Gm = Inf , Pm = 107 deg (at 2.24 rad/sec) 20

Magnitude (dB) Phase (deg)

-20

-40

-60 0

-45

-90

-135 10
-1

10

10

10

10

Frequency (rad/sec)

Figura 20. Mrgenes de ganancia y fase. INTRODUCCIN AL SIMULINK DE MATLAB Simulink es un programa con entorno grfico para modelacin y simulacin. Las diferentes libreras que posee, permiten representar sistemas dinmicos de una manera muy simple. Para invocar el Simulink, basta escribir desde el comand window. >> simulink Simulink tiene dos fases de utilizacin: la definicin del modelo a trabajar y el anlisis del mismo. Para la definicin del modelo, Simulink dispone de diferentes libreras. Cada una de ellas dispone de una serie de elementos que nos permiten crear y editar los diagramas de bloques utilizando el ratn. A continuacin se mencionan algunas de las libreras ms importantes y algunos de los bloques que se encuentran dentro de ellas. Continuos: Integradores, derivadores, funcin de transferencia, retardo de transporte, memorias, etc. Discretos: Funciones de transferencia discretas, filtros digitales, ZOH, espacio de estado discreto, etc. Matemtica: Sumadores, ganancias funciones trigonomtricas, matrices, etc. Fuentes: Escaln unitario, seno, ruido blanco, variables desde un archivo .mat, generadores de seales, etc. No-lineales: Switches, rels, saturadores, etc. Seales y sistemas: Entradas y salidas, multiplexores, demultiplexores. 31

Salidas: Displays, osciloscopios, salidas a archivos .mat o al espacio de trabajo. Para construir un modelo se empieza creando un archivo tipo model (File, New, model), y se abren los distintos grupos de funciones a utilizar, despus se colocan los bloques necesarios en la ventana que se cre, arrastrando con el ratn los bloques deseados hasta el rea de trabajo. Luego se procede a conectarlos por medio de un clic sostenido uniendo sus entradas y salidas. Despus se configuran los parmetros de cada bloque segn el modelo y posteriormente se trabaja en el men de simulacin con parmetros de cada tiempo de inicio, tiempo de finalizacin, etc. Despus, se inicia la simulacin (simulationstart) y por ltimo se observan los resultados por ejemplo haciendo doble clic sobre el scope (si es que se us alguno). Un ejemplo sencillo de la utilizacin de este paquete se muestra a continuacin. Sea la funcin de transferencia en lazo abierto: () = 2 + 1 + 3 + 5

La respuesta al escaln en lazo abierto puede determinarse implementando el diagrama mostrado en la siguiente figura:

Figura 21. Lazo Abierto. De igual forma, la figura 22 muestra el diagrama necesario para determinar la respuesta al escaln en lazo cerrado (con realimentacin unitaria).

Figura 22. Lazo Cerrado. Simulink es una herramienta muy til para simulacin de modelos sencillos como los mostrados en los ejemplos, pero tambin permite la creacin de modelos ms complejos ya sean estos continuos o discretos, multivariables y no lineales entre otros, ya que dispone de una serie de libreras especializadas y ayudas de programacin para los casos ms elaborados. ACTIVIDADES 1. Sea G y H dos funciones de transferencia que modelan el comportamiento de un sistema donde:
(4 2 +2+5) +3

Obtener el equivalente en serie y paralelo para los diagramas de bloques mostrados en la figura 23. Haga uso de los comandos feedback(G,H) y series(G,H).

() =

y () =

2.6+0.02

32

Figura 23. Diagramas para la Actividad. 2. Con el simulink construya el esquema de la figura 24 y visualice la respuesta del sistema para una entrada escaln unitario y rampa unitaria.

Figura 24. Diagrama en Simulink.

33

SCILAB

Master Scilab!
by Finn Haugen 2. April 2008

Contents:
1 What is Scilab? 2 About this document 3 Downloading and installing Scilab 4 The Scilab environment 5 Scilab Help 6 Scripts 7 Matrix operations 8 Plotting 9 Functions for dynamics and control 9.1 Simulation of continuous-time transfer functions 9.2 Frequency response of continuous-time transfer functions 9.3 Simulation of discrete-time transfer functions 9.4 Frequency response of discrete-time transfer functions 9.5 Simulation of continuous-time state-space models 9.6 Discretizing continuous-time systems 9.7 Deriving transfer functions from state-space models 9.8 Combining models: Series, parallel, and feedback 9.9 Frequency response analysis and simulation of feedback (control) systems 9.10 LQ (linear quadratic) optimal controller 9.11 Kalman Filter gains

1 What is Scilab?
Quoted from the homepage of Scilab at http://scilab.org: Scilab is a free scientific software package for numerical computations providing a powerful open computing environment for engineering and scientific applications. Scilab is an open source software. Since 1994 it has been distributed freely along with the source code via the Internet. It is currently used in educational and industrial environments around the world. Scilab includes hundreds of mathematical functions with the possibility to add interactively programs from various languages (C, C++, Fortran). It has sophisticated data structures (including lists, polynomials, rational functions, linear systems...), an interpreter and a high level programming language. Scilab is quite similar to Matlab, and the range of functions are comparable. The largest benefit of Scilab is of course that it is free :-). Also, Scilab is easy and fast to install (and you do not have to restart your PC before starting to use it). Scilab is also similar to Octave, which is also free! Octave is more similar to Matlab than to Scilab. One problem with Octave has been that data plotting is more cumbersome in Octave than in Scilab. (Yo can have both Scilab and Octave installed :-) One nice thing about Scilab is that you get Scicos automatically installed when you install Scilab. Scicos is a blockdiagram based simulation tool similar to Simulink and LabVIEW Simulation Module. 34

2 About this document


This tutorial guides you through the steps towards mastering Scilab. I have written this document because I did not find a proper tutorial on the Scilab homepage. I assume that you do all the activities in the blue boxes, as here: Activities are shown in blue boxes as this one. Please send comments or suggestions to improve this tutorial via e-mail to finn.haugen@hit.no.

3 Downloading and installing Scilab


The installation file, which is an *.exe-file, is available for download at http://scilab.org. Once you have downloaded this exe-file, open (run) it, and then follow the instructions on the screen. (It should not be necessary to restart your PC before you start Scilab after the installation.) Note that by installing Scilab, you also get Scicos installed.

4 The Scilab environment


To start Scilab: Double-click the Scilab icon on the PC desktop, or Go to Start / All Programs / Scilab / scilab (do not select scilab console). Start Scilab. Starting Scilab opens the Scilab command window, see the figure below.

The Scilab command window Scilab commands are executed at the command line by entering the command, and then clicking the Enter button on the keyboard. Execute 1+1 (type 1+1 at the command line, and finish with Enter-button). 35

The result is shown in the command window (see the figure above).

5 Scilab Help
Open Scilab Help by clicking the Help button in the toolbar (the button with the question mark). The Help window is shown below.

Scilab Help window As you see from the Help window, the commands and functions are organized in a number of categories. As an example, click the Elementary Functions category to see the functions in that category. The functions are as shown in the figure above. To get detailed help text about a specific function, click that function. 36

Click the abs function (in the Elementary Functions category). The detailed help text for the abs function is shown in the figure below.

The detailed help text for the abs function You can also search for a function by first clicking the Search button in the Help window (the magnifying glass button). Search for sine. The result of the search is a list of relevant functions, see the figure below.

37

The result of the search for sine

5 Basic Scilab operations


Typically you use variables in your calculations. To create the variable a and assigning to it the result of 1+1: a=1+1 (Enter) Hereafter, (Enter) will not be shown, but it is assumed that you click the Enter button. The response is shown in the command window (but shown here). Now, try (remember to type the semicolon): b=1+2; The response is not shown in the command window. The command was actually executed, but because of the semicolon the response was not shown. To verify that the variable b actually exists: b As you will see, it exists. If you omit the variable name, the result is assigned to the inbuilt variable ans: 2+2 The response shows that the variable ans has got the value 4. You can execute one or more commands - separated by semicolon or comma - on one line: c=2+3, d=2+4 Scilab is case-sensitive. For example, d and D are two different variables: d, D 38

As you see from the response (not shown here), d exists, while D does not exist (since we have not created D). Scilab variables exists in the workspace. There are two ways to see the contents of a workspace: Executing the command who at the command line, which just lists the variables in the command window. Menu Applications / Browser Variables, which opens the Browser Variables window. Execute the command who. The response should be similar to what is shown in the figure below. (The user-defined variables are shown among many other variables.)

The response of the command who Select the menu Applications / Browser Variables. This opens the Browser Variables window, see the figure below.

Browser Variables window 39

The Browser Variables window contains at the bottom a number of utility buttons (not described in detail here). Note that if you exit from Scilab, the variables you created in the workspace are deleted. You can save variables in a file using the save function. However, if you really need to save variables that are a result of some Scilab expressions, then you should consider writing these expressions in a Scilab script instead. More about scripts soon. There are various ways to enter numbers (the pi is an inbuilt constant). Here are some illustrative examples (I assume that you see the principles from these examples): 0.1, 1e-1, 2^3, exp(1), pi The response is shown in the figure below.

Various ways to enter numbers You can determine how numbers are displayed in the command window with the format function, but the internal representation of the number in Scilab is independent if the display format. We will not look at details. If you need to change the display format, consult Scilab Help. Scilab functions are vectorized, i.e. functions can be called with vectorial arguments. (A vector is simply a one-dimensional matrix. We will return to vector- and matrix operations in a later section.) In the following example, first a vector of name t is created, then this vector is used as an argument in the sine function (the sine function assumes the argument is an angle in radians). t=[0:10]', sin(0.1*t) The response is shown in the figure below.

40

The result of the vectorized function call sin(0.1*t) where t is a vector

6 Scripts
A Scilab script is a text file of name *.sce containing Scilab commands. You can edit the script using the inbuilt Scipad editor. (Scripts can also have names *.sci. The default name when saving a fle in Scipad is *.sce.) You should use scripts even for small tasks because in this way you have all your "projects" saved in files which is good for documentation and also very convenient when you want to run all your commands after some changes. We will now create a simple script, and then run it. Running a script is the same as executing all the commands (from top to bottom in the script) at the command line one by one. Launch the Scipad editor by selecting the Editor menu (or by executing the scipad command). Then enter the commands shown in the figure below. The Scipad editor is shown in the figure below. Note that double slashes (//) are used to start comments in the script.

41

Scilab script of name script1.sce opened in the Scipad editor Note that you can open several scripts in the same Scipad window with the File / New menu. Save the script with name script1.sce (of course some other name can be used) in the directory (folder) C:\temp or in any other directory you prefer. There are two ways to run the script1.sce script: With the Execute / Load into Scilab menu in Scipad By executing the command exec script1.sce at the command line Let us try the Execute menu first: Select the Execute / Load into Scilab menu in Scipad. The result is shown in the command window. Now let us try the exec command: Execute the command exec script1.sce at the command line. Scilab responds with an error! See below.

Scilab responds with an error when after executing the command exec script1.sce 42

The error comes because script1.sce is not in the Current directory of Scilab. The Current directory is the directory where Scilab looks for your script when you try to execute it with the exec command. What is then the present Current directory? Excute the menu File / Get Current Directory. The response (in the command window) may be different on different PCs. On my PC the response is C:\Documents and Settings\Finn Haugen\Skrivebord We saved script1.sce in the C:\temp directory which is different from the present Current Directory. Let us change the Current Directory to C:\temp, and then execute the script: Excute the menu File / Change Directory. This opens a window in which you select to become the Current directory. Execute the command exec script1.sce at the command line. Now the script should run without errors.

7 Matrix operations
In Scilab numbers are in general stored in matrices, which can be regarded as a table. Matrices with only one column or only one row are denoted vectors. (Matrices and vectors are very similar to arrays as used in programming languages as C, Visual Basic etc.) Creating matrices. Retrieving data from matrices Let us create a 2x2 matrix of name A. In general, comma (or space) is used to separate numers on a row (or line), and semicolon is used to separate rows. A=[1,2;3,4] The figure below shows A as displayed in the command window.

Creating and displaying the matrix A Create a row vector with first element 0, last element 1 and increment (step size) 0.2: r=[0:0.2:1] Create a column vector, note the apostrophe to transpose: c=[0:0.2:1]' Create matrix B from given column vectors x and y: x=[1,2,3]'; y=[4,5,6]'; B=[x,y] 43

Get the size (dimensions) of matrix B: size(B) Get the first element of vector r. Note that 1 (not 0) is the first index! r(1) Now try r(0) You get an error because index number 0 can not be used. Get the second column in matrix B, and assign the values to vector v: v=B(:,2) Some special matrices Create an identity matrix of dimension 2x2: C=eye(2,2) Create a matrix of dimension 3x2 consisting of ones: D=ones(3,2) Create a matrix of dimension 3x2 consisting of zeros: E=zeros(3,2) Matrix calculations Matrices can be used in matrix calculations. Add two matrices (assuming A and C have been created as explained above): F=A+C Multiply two matrices: G=A*C Take the inverse of a matrix: H=inv(A) Elementwise calculations Elementwise calculations are made with the dot operator. As an example, to perform elemenwise multiplication of two vectors: v1=[1,2], v2=[3,4], z=v1.*v2 The result is shown in the figure below. Element z(1) is v1(1)*v2(1), and element z(2) is v1(2)*v2(2).

Elementwise multiplication of two vectors 44

8 Plotting
The basic command for plotting data in a figure is plot. In the following are a number of examples demonstrating various plotting options. (It is of course up to you if you type the code from scratch on the command line or in Scipad, or if you just copy the code. If you type the commands, you may omit the comments which is the text following the // sign to save time.) First, let us generate some data that will be used in the following examples. t=[0:.1:10]'; //t is a column vector u=-1+0.2*t; //u is a column vector y=sin(2*t); //y is a column vector Very basic plotting: scf(1); //Opens (new) figure with ID 1. (scf = set current fig) plot(y) //Plots y against y-indexes (integers along x-axis) Below is shown the Scilab figure with the plot. Along the x-axis are the indexes of the y vector. The indexes are integers from 1 to 101.

Before we continue with more plotting commands, let us take a look at some buttons and menus in the Graphics window. Click the GED button in the figure window. This opens the Clicking the GED button opens the Graphics Editor, see the figure below.

45

The Graphics Editor With the graphics editor you can change line colours, line style, add labels to the axis, add grid, etc. The various options will not be described here because it is rather easy to investigate the possibilities by yourself. Many of the options in the Graphics Editor can alternatively be set with options to the plot command. This will be shown in subsequent examples. You can produce various graphics files from the plot: Select the menu File / Export in the figure window. This opens the Export dialog window shown below.

The Export dialog in the figure window 46

If you want to create a graphis file to put into a document processor, as MS Word or Scientific Workplace, you should select Enhanced Meta File (EMF), whch is a vectorized graphics format which means that the picture can be enlarged and still look sharp. However, EMF files can not be used in native web documents, e.g. in HTML-files to be displayed in a web browser. In this case you should select the GIF format (this format does not give you vectorized graphics). We continue with looking at more options to the plot command. Assume that we will plot y against t in Figure 1 which is the same figure as we used above. This is done with the command plot(t,y) where it is of course assumed that vectors t and y have the same length (same number of elements). If you just use the plot command, the new plot adds to the previous plot, showing two (or more curves). Typically, this is not what you want. To clear the previous plot, we use the clf (clear figure) command before we use the plot command. //Clears a plot, and plots in the same figure: scf(1); //Sets figure 1 to become current figure clf; //clears the figure plot(t,y) //Plots in figure 1 The result is shown in the figure below. Observe that the x-axis now contains the t values.

Suppose you want to show the plot in a new Figure 2 in stead of the previously opened Figure 1: scf(2); //Sets figure 2 to become current figure plot(t,y) //Plots in figure 1 To clear Figure 2: Just close the Figure 2 window by clicking the close button in the upper right corner of the window (or with the menu File / Close in the window). 47

To plot with with grid and plot title and labels: scf(1); //Opens (new) figure with ID 1. (scf = set current fig) plot(t,y) //Plots u against t ax1=gca();ax1.grid=[0,0];//Adds grid. (gca=get current axes) //[0,0] is colour code for x and y grid, resp. [0,0] is black. title('Experiment 1') xlabel('t [s]') ylabel('y [V]') The resulting plot is shown in the figure below. (If you think the code ax1=gca();ax1.grid=[0,0]; is too cumbersome for generating a grid, you can in stead use the Graphics Editor (by clicking the GED button in the figure window).)

To plot two curves in one plot (note the ordering of the vectors in the plot command): scf(1);clf; //Opens figure 1 and clears its present content plot(t,y,t,u) //Plots y against t, and u against t The result is shown in the figure below.

To plot two curves with options for the line style and colours: 48

scf(1); clf; //Opens and clears figure 1 plot(t,y,'r--',t,u,'b') //'r--' is red and dashes. 'b' is blue. (Many more options can be found from Help linespec.) The result is shown in the figure below.

To plot several subplots in one figure: scf(1); clf; //Opens and clears figure 1 subplot(211) //Plot number 1 in a 2x1 "table" of plots plot(t,u) subplot(212) //Plot number 2 in the 2x1 "table" of plots plot(t,y) The result is shown in the figure below.

Subplots 49

9 Functions for dynamics and control


In the following are examples of using Scilab functions for solving problems in the field of control engineering. The functions used are among the function in the General System and Control function category (see Scilab Help). 9.1 Simulation of continuous-time transfer functions The csim function is used to simulate continuous-time transfer functions. Here is one example: s=poly(0,'s'); //Defines s to be a polynomial variable K=1; T=1; //Gain and time-constant sys=syslin('c',K/(T*s+1)); //Creates sys as a continuous-time ('c') syslin model. t=[0:0.05:5]; //Time vector to be used in simulation y1=csim('step',t,sys); //Simulates system sys with step input scf(1);clf; //Opens and clears figure 1 plot(t,y1) ax1=gca();ax1.grid=[0,0]; //Adds grid to the plot u=sin(5*t); //Creates input signal y2=csim(u,t,sys); //Simulates system sys with u as input scf(2);clf; plot(t,y2); ax1=gca();ax1.grid=[0,0]; The two plots are shown in the figures below.

Step response

50

Sinusoid response 9.2 Frequency response of continuous-time transfer functions The bode function plots frequency response in a Bode plot. Here is one example: s=poly(0,'s'); //Defines s to be a polynomial variable K=1; T=1; //Gain and time-constant sys=syslin('c',K/(T*s+1)); //Creates H1 as a continuous-time ('c') syslin model. fmin=0.01; //Min freq in Hz fmax=10; //Max freq in Hz scf(1);clf; bode(sys,fmin,fmax); //Plots frequency response in Bode diagram The Bode plot is shown in the figure below.

Bode plot 51

The bode function does not accept models with time-delay. However, there is a workaround to this problem that can be downloaded from here. 9.3 Simulation of discrete-time transfer functions The flts function can be used to simulate a discrete-time transfer function. Here is one example: z=poly(0,'z'); //Defines z to be a polynomial variable a=0.1; //Parameter in transfer function sys=syslin('d',a*z/(z-(1-a))); //Creates sys as a discrete-time ('d') syslin model. u=ones(1,50); //Defines input signal as a series of ones y=flts(u,sys); //Simulates the system with u as input scf(1);clf;plot(y); //Plots response y ax1=gca();ax1.grid=[0,0]; //Adds grid to the plot Comment to the transfer function in this example: It is a*z/(z-(1-a)) = y(z)/u(z) where y is output and u is input. This transfer function is "by chance" the transfer function corresponding to the difference equation y(k) = (1-a)*y(k) + a*u(k) which is the well-known EWMA lowpass filter (Exponentially Weighted Moving Average) frequently used in applications where a simple filter is needed, as in control systems where a lowpass filter is used to attenuate measurement noise from the sensor. The simulated response is shown in the figure below.

Step response

52

9.4 Frequency response of discrete-time transfer functions The bode function plots frequency response in a Bode plot. Here is one example: z=poly(0,'z'); //Defines z to be a polynomial variable a=0.1; //Parameter in transfer function sys=syslin('d',a*z/(z-(1-a))); //Creates sys as a discrete-time ('d') syslin model. fmin=0.001; //Min freq in Hz fmax=1; //Max freq in Hz scf(1);clf; bode(sys,fmin,fmax); //Plots frequency response in Bode diagram The Bode plots are shown in the figure below.

Bode plots of discrete-time transfer function Comments about frequency information: The frequency axis shows normalized frequencies. The red vertical line in the Bode plots represents the normalized Nyquist frequency, which is 0.5, corresponding to the normalized sampling frequency being 1 samples/sec. If the actual sampling 53

frequency is f s [samples/sec], the actual (non-normalized) frequency is found by multiplying the normalized frequency by f s . 9.5 Simulation of continuous-time state-space models The state-space model is assumed to be dx/dt = A*x + B*u y = C*x + D*u with x0 as initial state. In the following example, first the state-space model is defined, then the responses due to initial state and to external input signal u are simulated using the csim function, and finally the responses in output y and in state-variables x are plotted. A=[0,1;-1,-0.5];B=[0;1];C=[1,0];D=[0]; //System matrices x0=[1;0]; //Initial state sys=syslin('c',A,B,C,D,x0); //Creates sys as cont.-time ('c') state-space model. t=[0:0.1:50]; //Time vector to be used in simulation u=0.5*ones(1,length(t)); //Creates constant input signal [y,x]=csim(u,t,sys); //Simulates sys with u as input. y is output. x are states. scf(1);clf; //Opens and clears figure 2 plot(t,y); //Plots response in y ax1=gca();ax1.grid=[0,0]; //Adds grid to the plot scf(2);clf; //Opens and clears figure 2 plot(t,x); //Plots response in x ax1=gca();ax1.grid=[0,0]; //Adds grid to the plot The figures below show the response in the output y and in the state-variables x, respectively.

The response in the output y 54

The response in the state-variables x 9.6 Discretizing continuous-time systems The function dscr is used to discretize continuous-time models. dscr only handles state-space models. So, if you are to discretize transfer functions, you have to convert the original continuous-time transfer function into a state-space model (using the tf2ss function) before you use dscr. And thereafter, you convert the discrete-time state-space model to the (final) transfer function (using the ss2tf function). Here is one example: s=poly(0,'s'); //Defines s to be a polynomial variable TFcont=syslin('c',[1/(s+1)]) //Creating cont-time transfer function SScont=tf2ss(TFcont); //Converting cont-time transfer function to state-space model Ts=0.1; //Sampling time SSdisc=dscr(SScont,Ts); //Discretizing cont-time state-space model TFdisc=ss2tf(SSdisc) //Converting discr-time ss model to tf The original continuous-time transfer function TFcont and the resulting discrete-time transfer function TFdisc are shown in the figure below.

The original TFcont and the resulting TFdisc 55

Although it is not written in the help text of dscr you can assume that the discretization is based on the exact discretization with zero-order hold (piecewise constant input during the time steps) on the input of the system. (The result of using the c2d function in Matlab with zero-order hold one the above example gives the same result as above.) 9.7 Deriving transfer functions from state-space models The function ss2tf derives transfer function(s) from a state-space model: A=[0,1;-1,-0.5];B=[0;1];C=[1,0];D=[0]; //System matrices of original state-space model SS=syslin('c',A,B,C,D); //Creates SS as continuous-time ('c') state-space model TF=ss2tf(SS) //Resulting transfer function The resulting transfer function is shown in the figure below.

The resulting transfer function TF 9.8 Combining models: Series, parallel, and feedback Here are examples of how to calculate the combined transfer function for series, parallel, and feedback combination of models (here transfer functions): s=poly(0,'s'); //Defines s to be a polynomial variable sys1=syslin('c',[1/s]) //Creating transfer function sys1 sys2=syslin('c',[(2+0*s)/(1+0*s)]) //Creating transfer function sys2, which is gain 2 sys_series=sys1*sys2 //Calculating resulting transfer function of a series combination (multiplication) sys_parallel=sys1+sys2 //Calculating resulting transfer function of a parallel combination (summation) sys_feedback=sys1/.sys2 //Calculating resulting transfer function of a negative feedback combination //where sys1 is in the feedforward path, and sys2 is in the feedback path. Negative feedback is assumed. The results are shown in the figure below (you should verify the results by hand calculations).

56

Results of series, parallel, and feedback combination of the transfer functions sys1 and sys2 9.9 Frequency response analysis and simulation of feedback (control) systems The gain margin and phase margin and the corresponding frequencies can be calculated with g_margin and p_margin functions. Here is an example: s=poly(0,'s'); //Defines s as polynomial variable F=syslin('c',[0.5/((1+s)*(1+s)*s)]); //Creates transfer function in forward path B=syslin('c',(1+0*s)/(1+0*s)); //Creates transfer function in backward path OL=F*B; //Calculates open-loop transfer function CL=F/.B; //Calculates closed-loop transfer function [GainMargin,freqGM]=g_margin(OL) //Calculates gain margin [dB] and corresponding frequency [Hz] [Phase,freqPM]=p_margin(OL) //Calculates phase [deg] and corresponding freq [Hz] of phase margin PhaseMargin=180+Phase //Calculates actual phase margin [deg] fmin=0.01; //Min freq in Hz fmax=1; //Max freq in Hz scf(1);clf; bode(OL,fmin,fmax); //Plots frequency response of open-loop system in Bode diagram t=[0:0.1:40]; //Time vector for simulation yref=ones(1,length(t)); //Reference (setpoint) of the control system 57

y=csim(yref,t,CL); //Simulates closed-loop system scf(2);clf; plot(t,y,t,yref) //Plots control system output and its reference ax1=gca();ax1.grid=[0,0]; //Grid CL_ss=tf2ss(CL); //Converts closed-loop transfer function to state-space model A_CL=CL_ss('A') //Calculates eigenvalues of A-matrix of closed-loop model The calculated stability margins and crossover frequencies are shown in the figure below. The gain margin and the phase margin are larger than zero, and hence the control system is asymptotically stable.

Calculated stability margins and crossover frequencies The Bode plot of the open-loop system is shown in the figure below.

Bode plot of open-loop system 58

The process output and its reference is shown in the figure below.

Simulation of closed-loop system The eigenvalues of the closed-loop system are calculated with the spec function, cf. the script above. The result is shown in the figure below. All eigenvalues have negative real part, and hence it is confirmed that the control system is asymptotically stable.

Eigenvalues (poles) of the closed-loop system 59

9.10 LQ (linear quadratic) optimal controller Given the following discrete-time state-space model: x(k+1) = A*x(k) + B*u(k) The lqr function (linear quadratic regulator) can be used to calculate the steady-state controller gain, K, of the controller u(k) = K*x(k) that minimizes the linear quadratic cost function J = sum 0 inf[x'(k)*Q*x(k) + u'(k)*R*u(k)) There is one problem with the lqr function, namely that the user can not define the weight matrices Q and R directly as arguments to the function, but in stead some intermediate calculations have to be done. A more user-friendly way to solve the control design task is to use the Riccatti solver ricc in Scilab [reference] (an Riccatti equation is solved as a part of the design algorithm). Here is one example: A=[1,0.4;0,0.6];B=[0.1;0.4]; //Model Q=[1,0;0,0.04];R=[1]; //Weights P=ricc(A,B/R*B',Q,"disc"); //P becomes solution to Riccatti equation K=-inv(R+B'*P*B)*B'*P*A //K is the steady-state controller gain eig_control_syst=spec(A+B*K) //Eigenvalues of closed-loop system //The eigenvalues will be inside unity circle since control system is asymptotically stable. The controller gain and the eigenvalues are shown in the figure below.

Controller gain and eigenvalues of LQ optimal control system (The Matlab function dlqr gave the same result.) 9.11 Kalman Filter gains Steady-state Kalman Filter gains for continuous-time systems and for discrete-time systems can be computed with the lqe function. For discrete-time systems the Kalman Filter is assumed to have the one-step form (combined prediction and measurement update), and not on the probably more popular two-step form (separate measurement update and prediction update).

60

Master Scicos!
by Finn Haugen 8. July 2008

Contents:
1 What is Scicos? 2 About this document 3 The Scicos environment 4 An example: Simulator of a liquid tank 4.1 Developing the mathematical model of the system to be simulated 4.2 Downloading and running the simulator 4.3 Studying the simulator 4.4 Constructing the block diagram

1 What is Scicos?
Scicos is a block-diagram based simulation tool, which means that the mathematical model to be simulated is represented with function blocks. Scicos is quite similar to Simulink and LabVIEW Simulation Module. Scicos can simulate linear and nonlinear continuous-time, and discrete-time, dynamic systems. You can make the simulation run as fast as the computer allows, or you can make it run with a real or scaled time axis, thus simulating real-time behaviour. Scicos is automtically installed when you install the mathematical tool Scilab. You can not install Scicos independently of Scilab. Here is information about installing Scilab. The homepage of Scicos is at http://scicos.org.

2 About this document


This tutorial guides you through the basic steps towards mastering Scicos. I have written this document because I did not find a proper, updated tutorial on the Scicos homepage (there are however books about Scicos). I assume that you do all the activities in the blue boxes, as here: Activities are shown in blue boxes as this one. Please send comments or suggestions to improve this tutorial via e-mail to finn.haugen@hit.no.

3 The Scicos environment


First: Launch Scilab. To launch Scicos: Either enter scicos at the Scilab command line (or Select Applications / Scicos in the Scilab menu). The figure below shows the Scicos window where you will construct the (block) diagram.

61

The Scicos window The blocks that is used to build the mathematical model to be simulated are organized in palettes. (When you construct a diagram you simply drag blocks from the palettes to the block diagram.) To display the palettes in a tree structure: Select Palettes / Pal tree in the Scicos menu. The figure below shows the palettes.

62

The block palettes To see the individual blocks on a specific palette, click the plus sign in front of the palette. As an example, display the blocks on the Sources palette. The figure below shows some of the blocks on the Sources palette.

63

Some of the blocks on the Sources palette An alternative way to open a specific palette is selecting the palette via the Palette / Palettes menu: As an example, select the Sources palette via the Palette / Palettes menu. The figure below shows (again) the Sources palette (this time all the blocks are shown).

64

The Sources palette You can even open the palettes in this way: As an example, open the Sources palette via Right-click on the block diagram / Select Palettes (in the menu that is opened). It is useful to see the contents of the various palettes. Hence, in the following, the palettes are shown, and comments about selected (assumably) most useful blocks on the palettes are given. Here are comments to selected blocks on the Sources palette shown above: Activation clock (red clock) is used to activate or invoke other blocks with a specified period, e.g. Scope blocks and Display blocks. Clock generates a signal which value is the simulation time. Constant (square block with "1" inside) generates a constant, or a parameter having a constant value. Step generated a step from an initial value to a final value at a specific point of time. The Sinks palette:

65

The Sinks palette


Comments to selected blocks in the Sinks palette: Scope is used to plot signals as the simulation runs. Using a Mux block (on the Branching palette) you can merge a number of scalar signals into to be plotted in one Scope. Display is used to display the numerical value of any signal. To workspace is used to save a signal as a variable in the workspace of Scilab. The resulting variable is of mlist data type (you can learn more about mlist data type via Help in Scilab). The mlist variable will consist of the time-stamps and the signal values. Below is some example code (to be executed in Scilab, and remember to close Scicos before you attempt to execute code in Scilab) that illustrates how to get the time and the signal as individual arrays or vectors from the variable of mlist data type. In the example, these arrays are used as arguments in the plot command. Assume that you have given the name V to the workspace variable to be gernerated by the To workspace block. In the following t is chosed as the name of the time, and x is chosen as the name of the signal. t=V.time; x=V.values; plot(t,x) The Linear palette:

66

The Linear palette


Comments to selected blocks in the Linear palette: Sum (block) can be used to sum and/or subtract signals. The block is configured by double-clicking the block. Gain represents a gain, i.e. multiplication by a constant. (The triangular block with 1 inside.) Integrator is used to time-integrate signals that are time-derivatives of the state-variables of the system. The integrator output is then state-variables of the system. (Thus, the integrators implement the dynamics of the system.) The initial value and the maximum and minimum values of the integrator output can be set. PID is a PID controller (Proportional + Integral + Derivative). The parameters are proportional gain Kp, integral gain Ki, and derivative gain Kd. Often the PID parameters are in stead given as Kp, integral time Ti, and derivative time Td. (The famous Ziegler-Nichols' PID controller tuning method gives values for Kp, Ti and Td.) The relation between the various parameters are as follows: Ki = Kp/Ti and Kd = Kp*Td. Continuous fix delay (Time delay) represents a time delay, also denoted dead-time and transport delay. At the start of the simulation, the block outputs the Initial input parameter until the simulation time exceeds the Time delay parameter, when the block begins generating the delayed input. Continuous-time (Laplace transform) transfer function (the num(s)/den(s) block). You configure the block by entering the numerator and denominator s-polynomials. Discrete-time (z transform) transfer function (the num(z)/den(z) block). You configure the block by entering the numerator and denominator z-polynomials. Unit delay block (with symbol 1/z inside) which implements delay of one time step. The Nonlinear palette: 67

The Nonlinear palette


Comments to selected blocks in the Nonlinear palette: Mathematical Expression is used to implement any Scilab function (you type the expression in the dialog box of the block). Product implements multiplication or division. It takes any number of inputs. Interp implements interpolation or table lookup between tabular data. The Others palette:

68

The Others palette


Comments to selected block on the Others palette: Text is used to add annotations (any text) to the block diagram. End can be used to stop the simulation at a specific simulation time. The Branching palette:

69

The Branching palette


Comments to a selected block on the Branching palette: Mux is used to merge a number of scalar signals into a vectorized ("multivariable") signal. This block is useful e.g. to merge several signals to be plotted in one Scope. Switch 1 can be used to select which of the inputs (among any number of inputs) to be propagated to the output.

4 An example: Simulator of a liquid tank


In this section we will study a premeade simulator of a liquid tank. Then, you will learn how to create a simulator by yourself. You are supposed to have basic knowledge about modeling of dynamic systems, as described in e.g. Dynamic Systems - modelling, analysis and simulation or in any other book about dynamic systems theory. 4.1 Developing the mathematical model of the system to be simulated The system to be simulated is a liquid tank with pump inflow and valve outflow, see the figure below. The simulator will calculate and display the level h at any instant of time. The simulation will run in real time, thereby giving the feeling of a "real" system. Actually, since this tank is somewhat sluggish, we will speed up the simulation to have the simulation time running faster than real time, to avoid us waste our precious time. The user can adjust the inlet by adjusting the pump control signal, u.

70

Liquid tank Any simulator is based on a mathematical model of the system to be simulated. Thus, we start by developing a mathematical model of the tank. We assume the following (the parameters used in the expressions below are defined in the figure above): The liquid density is the same in the inlet, in the outlet, and in the tank. The tank has straight, vertical walls. The liquid mass and level are related through m(t) = Ah(t) The inlet volumetric flow through the pump is proportional to the pump control signal: q in (t) = K u u(t) The outlet volumetric flow through the valve is proportional to the square root of the pressure drop over the valve. This pressure drop is assumed to be equal to the hydrostatic pressure at the bottom of the tank (sqrt means square root): q out (t) = K v sqrt[gh(t)] Mass balance (i.e., rate of change of the mass is equal to the inflow minus the outflow) yields the following differential equation: dm(t)/dt = q in (t) - q out (t)] (1) or, using the above relations, d[Ah(t)]/dt = K u u(t) - K v sqrt[gh(t)] (2) We will now draw a mathematical block diagram of the model. This block diagram will then be implemented in the block diagram of the simulator VI. As a proper starting point of drawing the mathematical block diagram, we write the differential equation as a state-space model, that is, as a differential equation having the first order time derivative alone on the left side. This can be done by pulling and A outside the differentiation, then dividing both sides by A. The resulting differential equation becomes d[h(t)]/dt = (1/A)*{K u u(t) - K v sqrt[gh(t)]} (3) 71

This is a differential equation for h(t). It tells how the time derivative dh(t)/dt can be calculated. h(t) is calculated (by the simulator) by integrating dh(t)/dt with respect to time, from time 0 to time t, with initial value h(0), which we here denote h init . To draw a block diagram of the model (3), we may start by adding an integrator to the empty block diagram. The input to this integrator is dh/dt, and the output is h(t). Then we add mathematical function blocks to construct the expression for dh/dt, which is the right side of the differential equation (3). The resulting block diagram for the model (3) can be as shown in the figure below.

Mathematical block diagram of Differential Equation (3) The numerical values of the parameters are as follows: rho=1000; //[kg/m3] g=9.81; //[m/s2] Kv=0.0005; Ku=5; //[m3/A] A=1; //[m2] h_init=0.5; //[m] h_max=1; //[m] h_min=0; //[m] We will assume that there are level "alarm" limits to be plotted together with the level in the simulator. The limits are h_AH = 0.9 m (Alarm High) h_AL = 0.1 m (Alarm Low) 4.2 Downloading and running the simulator Download the premade simulator tanksim.cos, and save it in the folder you prefer. Open it in Scicos using the File / Open menu. Run the simulator using the Simulate / Run menu. In the simulation the initial value of the level is 0.5 m. The pump control signal u is 0 up to simulation time 20 s, and at 20 s it is changed as a step from 0 to 0.01 A. The simulator runs five times faster than real time. The simulator from initial time of 0 s to final time of 50 s. If you want to stop the simulator before the final time, select Stop in the Scicos menu. The figure below shows the block diagram of tanksim.cos.

72

The block diagram of tanksim.cos The figure below shows the simulated pump control signal u. The subsequent figure shows the response in the level h and the level alarm values h_AL and h_AH.

73

The simulated pump control signal u

74

The response in the level h and the level alarm values h_AL = 0.1 m and h_AH = 0.9 m Setting up the simulator Open the Simulate / Setup menu. This opens the dialog window shown in the figure below. 4.3 Studying the simulator

The dialog window opened with the Simulate / Setup menu. 75

Most parameters can generally be left unchanged in this dialog window, except the following parameters: The Final integration time defines the final (stop) time of the simulation. But, if an End block exists in the block diagram, the Final simulation time parameter in that block also defines the simulation stop time. It turns out that the applied stop time is the smallest of the two. In this example, I want the stop time to be 50 sec, and I want to use the End block with the Context variable t_stop to define the stop time. Therefore, I have set the Final integration time in the Setup dialog window to be larger than t_stop = 50, namely 10000. The Realtime scaling parameter defines the relative speed of the real time compared to the simulated time. In this example Realtime scaling is 0.2 which means that the real time runs 0.2 times as fast as the simulated time. In other words, the simulator runs 1/0.2 = 5 times faster than real time. You can use this parameter to speed up or slow down the simulator. E.g. it may be convenient to speed up the simulation of a slow system, and to slow down the simulation of a fast system (so that you are able to follow the simulated response at it develops in the scopes). The maximum step size can be set to a proper value, e.g. one tenth of the quickest time-constant (or apparent time-constant) of the system to be simulated. In our example we can set it to the timestep parameter in the Context (Scicos then automatically enters the numerical value of the Context parameter in the maximum step size field). The solver method (i.e. the numerical method that Scicos uses to solve the underlying algebraic and differential equations making up the model) can be selected via the solver parameter, but in most cases the default solver can be accepted. Close the simulation setup dialog window. How does Scicos know what is the time unit in the simulator? Hours? Minutes? Seconds? The answer is that you must define the time unit yourself, and you do it by determining the time unit of the timedependent parameter values, for example whether a mass flow parameter is given in kg/s or kg/min, etc. A general advice is to use seconds. Remember to use the selected time unit consistently in the simulator! Defining model (block) parameters in the Context Model parameters and simulation parameters can be set in the Context of the simulator. The Context is simply a number of Scilab expressions defining the parameters (or variables) and assigning them values. These parameters are used in the blocks in the diagram. Open the Context via the Diagram / Context menu. The Context of tanksim.cos is as follows: t_stop=50; //[s] timestep=0.1; //[s] rho=1000; //[kg/m3] g=9.81; //[m/s2] Kv=0.0005; Ku=5; //[m3/A] A=1; //[m2] h_init=0.5; //[m] h_max=1; //[m] h_min=0; //[m] h_AH=0.9; //[m] h_AL=0.1; //[m] t_u_step=20; //[s] u0=0; //[A] u1=0.01; //[A] 76

o o o

As an example, open the Step input block (by double-clicking) it, and observe that the Context variables t_u_step, u0, and u1 (see above) are used as parameters in the block. It is actually not necessary to use Context variables in blocks. You can use numerical values directly. But let me give you a good advice: Use Context variables! Because then all the parameter values appears only one place, not scattered around and "hidden" in the block diagram. The Activation clock block The Activation clock block activates the Scope blocks and the Display block. Open the Activation clock block. The Activation clock block contains the Init time parameter which in our example is set to the Context variable t_start, and the Period parameter which is set to the Context variable timestep. The period defines the time interval (period) between each time the adjacent blocks are activated. Close the Activation clock block. 4.4 Constructing the block diagram You construct the block diagram by dragging blocks from the relevant palette to the block diagram. Then you connect the blocks (this is done in the natural way using the mouse on the computer). You configure a block by double-clicking it and entering numerical or (preferably) a Context variable (parameter) name. Here are couple of tips regarding constructing block diagrams: You draw a new branch from an existing wire by double-clicking the wire, and then drawing the new branch. You can enter annotations at any place in the block diagram using the Text block on the Others palette. There are many options available while constructing the block diagram via Edit menu Format menu Right-click on the block diagram You can temporarily (while working with Scicos) perform calculations in the Scilab window via the menu Tools / Activate Scilab window. You can put a selected part of the block diagram into a super block via the menu Diagram / Region to Super Block. Remember to save your simulator regularly (File / Save menu). Play with tanksim.cos! Remove some of the blocks, then insert them from their respective palettes. Also try to edit the Context by adding (and possibly later removing) some commands, e.g. one or more new variables including comments about the variables. Finally, make sure you are able to run your simulator.

Bibliografia: http://es.wikipedia.org/wiki/MATLAB http://www.mat.ucm.es/~jair/matlab/notas.htm#programacion http://home.hit.no/~finnh/scilab_scicos/index.htm http://home.hit.no/~finnh/scilab_scicos/scilab/index.htm http://home.hit.no/~finnh/scilab_scicos/scicos/index.htm

77