02-introduccion al matlab y scilab

77
1 SISTEMAS AUTOMÁTICOS DE CONTROL INTRODUCCIÓN AL MANEJO DE MATLAB Y SCILAB Santiago de Cali Universidad del Valle Facultad de Ingeniería Escuela de Ingeniería Eléctrica y Electrónica 2010

Upload: fernando-figueroa

Post on 13-Oct-2014

706 views

Category:

Documents


11 download

TRANSCRIPT

Page 1: 02-Introduccion Al Matlab y Scilab

1

SISTEMAS AUTOMÁTICOS DE CONTROL INTRODUCCIÓN AL MANEJO DE MATLAB Y SCILAB

Santiago de Cali Universidad del Valle Facultad de Ingeniería

Escuela de Ingeniería Eléctrica y Electrónica 2010

Page 2: 02-Introduccion Al Matlab y Scilab

2

MATLAB

MATLAB (abreviatura de MATrix LABoratory, "laboratorio de matrices") es un software matemático que ofrece un entorno de desarrollo integrado (IDE) con un lenguaje de programación propio (lenguaje M). Está disponible para las plataformas Unix, Windows y Apple Mac OS X. Entre sus prestaciones básicas se hallan: la manipulación de matrices, la representación de datos y funciones, la implementación de algoritmos, la creación de interfaces de usuario (GUI) y la comunicación 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 simulación multidominio) y GUIDE (editor de interfaces de usuario - GUI). Además, 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 investigación y desarrollo. En los últimos años ha aumentado el número de prestaciones, como la de programar directamente procesadores digitales de señal o crear código 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 pestaña correspondiente. El Workspace contiene información sobre todas las variables que se hayan definido en esta sesión. La ventana inferior izquierda es

Page 3: 02-Introduccion Al Matlab y Scilab

3

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 botón derecho del ratón 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 cálculos que no se asignan a una variable en concreto se asignan a la variable de respuesta por defecto que es ans (del inglés, answer): >>2+3 ans =

5 Sin embargo, si el cálculo 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 añade un punto y coma (;) al final de la instrucción, la máquina no muestra la respuesta... >>y=5*4; ... pero no por ello deja de realizarse el cálculo. >>y y =

20 Las operaciones se evalúan por orden de prioridad: primero las potencias, después las multiplicaciones y divisiones y, finalmente, las sumas y restas. Las operaciones de igual prioridad se evalúan de izquierda a derecha: >>2/4*3 ans =

1.5000 >>2/(4*3) ans =

0.1667

Se pueden utilizar las funciones matemáticas habituales. Así, por ejemplo, la función coseno, >>cos(pi) %pi es una variable con valor predeterminado 3.14159... ans =

-1 o la función exponencial >>exp(1) %Función exponencial evaluada en 1, es decir, el número e

Page 4: 02-Introduccion Al Matlab y Scilab

4

ans = 2.7183

Además 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 máquina. Obsérvese que MATLAB trabaja en doble precisión ans =

2.2204e-016 pero... >>eps=7 eps =

7 Otro ejemplo de función matemática: la raíz cuadrada; como puede verse, trabajar con complejos no da ningún 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 número de decimales con que aparece en pantalla el valor de las variables, sin olvidar que ello no está relacionado con la precisión con la que se hacen los cálculos, 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 estándar 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 más información (obsérvese que todas las variables son arrays): >>whos Name Size Bytes Class Attributes ans 1x1 8 double array eps 1x1 8 double array x 1x1 8 double array y 1x1 8 double array

Page 5: 02-Introduccion Al Matlab y Scilab

5

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 trasposición (en realidad trasposición y conjugación): >>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 más que escribir el nombre del vector y, entre paréntesis, su índice: >>vect2(3) ans =

4 y se pueden extraer subvectores, por ejemplo: >>vect2(2:5) ans=

2 4 6 8 o, >>vect1(:)

Page 6: 02-Introduccion Al Matlab y Scilab

6

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' %Su traspuesta (su adjunta) ans =

1 4 7 2 5 8 3 6 9

>>mat=[v;w;0 0 1] %También es una matriz 3x3 mat =

1 2 3 4 5 6 0 0 1

A los elementos de una matriz se accede sin más que escribir el nombre de la matriz y, entre paréntesis, los respectivos índices: >>mat(1,3) %Elemento en la primera fila y tercera columna de la matriz mat ans =

3 También se puede acceder a una fila o columna completas, >>mat(:,2) %Segunda columna de mat ans =

2 5 0

>>mat(2,:) %Su segunda fila

Page 7: 02-Introduccion Al Matlab y Scilab

7

ans = 4 5 6

acceder a la matriz como si fuera una columna, >>M(2:7) %Los elementos segundo a séptimo 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 están 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 inglés 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 tamaño de una matriz y la longitud de un vector: >>size(mat) %Dimensiones de la matriz mat (número de filas y de columnas) ans =

3 3 >>size(v) ans =

1 3

Page 8: 02-Introduccion Al Matlab y Scilab

8

>>length(v) %Longitud del vector (número 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 matemáticas elementales están definidas de forma que se pueden aplicar sobre arrays. El resultado es el array formado por la aplicación de la función 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 =

Page 9: 02-Introduccion Al Matlab y Scilab

9

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 %Recordamos el valor de la matriz mat mat =

1 2 3 4 5 6 0 0 1

>>mat^2 %Matriz mat elevada al cuadrado ans =

9 12 18 24 33 48 0 0 1

También pueden efectuarse multiplicaciones, divisiones y potencias de arrays, entendiéndolas 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

Page 10: 02-Introduccion Al Matlab y Scilab

10

>>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 versátil comando \: >>mat\v' ans =

2.6667 -5.3333 3.000

VARIABLES LÓGICAS También existen variables lógicas que toman los valores 0 (falso) o 1 (verdadero). Por ejemplo: >>abs(v)>=2 %Vector lógico 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 %Asignación de un valor lógico (el doble signo igual es el %igual lógico) logica =

0 1 0 >>logic2=v~=v2 %Distinto (~ es el operador de negación) logic2 =

1 0 1

Page 11: 02-Introduccion Al Matlab y Scilab

11

POLINOMIOS Se puede trabajar con polinomios: basta tener en cuenta que un polinomio no es más 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] %Polinomio 2*x^2+x q =

2 1 0 MATLAB tiene funciones específicas para polinomios como: >>polyval(p,-1) %Evaluación 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) %Raíces 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 mónico que tiene por raíces a los %números i, -i, 0.5 y pi ans =

1.0000 -3.6416 2.5708 -3.6416 1.5708 DERIVADAS Y PRIMITIVAS Dentro del módulo (toolbox) de matemática simbólica, se utiliza el programa de cálculo simbólico MAPLE. Con estas herramientas, se puede trabajar con funciones, >>f='sin(x)' %Función sin(x) definida mediante una cadena de caracteres f = sin(x) calcular derivadas, >>diff(f) ans =

Page 12: 02-Introduccion Al Matlab y Scilab

12

cos(x) >>diff(f,2) %Derivada segunda de f ans = -sin(x) o encontrar primitivas. >>int('log(x)') %Primitiva de la función logaritmo ans = x*log(x)-x >>diff('x*log(x)-x') %Comprobación ans = log(x) GRÁFICAS DE FUNCIONES MATLAB tiene un gran potencial de herramientas gráficas. 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

Figura 2. Gráfico xsin(x)

Como se ve, con pocos puntos la gráfica tiene un aspecto demasiado lineal a trozos. Para "engañar" al ojo, basta tomar más puntos.

0 0.5 1 1.5 2 2.5 3 3.50

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

Page 13: 02-Introduccion Al Matlab y Scilab

13

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

Figura 3. Gráfica xsin(x) más definida.

También pueden dibujarse funciones. Así: >>fplot('sin(x)',[0 2*pi]) %Dibuja la función seno en el intervalo [0,2*pi]

Figura 4. Gráfico con la función fplot.

-4 -3 -2 -1 0 1 2 3 40

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

0 1 2 3 4 5 6-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Page 14: 02-Introduccion Al Matlab y Scilab

14

>>hold on %Mantiene en la ventana gráfica los dibujos anteriores >>fplot('cos(x)',[0 2*pi]) %Dibuja sobre la gráfica anterior la función cos(x)

Figura 5. Gráfico 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 función x^2*sin(1/x)

Figura 6. Otro gráfico de una función.

0 1 2 3 4 5 6-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

-0.05 -0.04 -0.03 -0.02 -0.01 0 0.01 0.02 0.03 0.04 0.05-2.5

-2

-1.5

-1

-0.5

0

0.5

1

1.5

2

2.5x 10

-3

Page 15: 02-Introduccion Al Matlab y Scilab

15

También puede usarse el versátil comando ezplot (se lee como easy plot) que permite dibujar funciones, >>ezplot('exp(x)') %Dibuja la función exponencial en un intervalo adecuado a la función

Figura 7. Gráfico de una función exponencial.

curvas en paramétricas, >>ezplot('sin(t)','cos(t)',[0 pi])

Figura 8. Gráfico de una función paramétrica.

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

0

50

100

150

200

250

x

exp(x)

-0.5 0 0.5 1 1.5-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x

y

x = sin(t), y = cos(t)

Page 16: 02-Introduccion Al Matlab y Scilab

16

e implícitas >>ezplot('x^2 - y^2 - 1')

Figura 9. Gráfico de una función implícita.

También permite dibujar superficies. La forma más sencilla es mediante el comando ezsurf, >>ezsurf('sin(x*y)',[-2 2 -2 2])

Figura 10. Gráfico de una superficie.

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

-4

-2

0

2

4

6

x

y

x2-y2-1 = 0

-2-1

01

2

-2-1

0

12

-1

-0.5

0

0.5

1

x

sin(x y)

y

Page 17: 02-Introduccion Al Matlab y Scilab

17

aunque se pueden realizar gráficas más 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 ratón java.lang.NullPointerException at com.mathworks.jmi.bean.MatlabBeanInterface.addCallback(MatlabBeanInterface.java:680) at com.mathworks.jmi.bean.MatlabCallbackInterface.addCallback(MatlabCallbackInterface.java:128)

Figura 11. Otra superficie.

PROGRAMACIÓN Para escribir un programa con MATLAB habrá que crear un fichero que tenga extensión .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 dinámica, por lo que no es necesario declarar las variables que se van a usar. Por esta misma razón, 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 sesión), porque esto podría provocar

00.002

0.0040.006

0.0080.01

900

950

1000

10500

10

20

30

40

50

Page 18: 02-Introduccion Al Matlab y Scilab

18

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 más. Un programa escrito en MATLAB admite la mayoría de las estructuras de programación al uso y su sintaxis es bastante estándar. 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 términos de la sucesión 1, 2x, 3x^2, 4x^3, ... n=input('¿Cuántos términos 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 número natural es primo. n=input('Número 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 número dado es primo.') else disp('El número dado no es primo.') disp('De hecho, es divisible por:') disp(i) end Programa 3: Escribir un número natural en una base dada (menor que diez). n=input('Dame el número 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 expresión en la base dada es:') i=i-1; disp(c(i:-1:1)) Por último, también pueden programarse funciones. La primera instrucción de un fichero que contenga una función de nombre fun debe ser: function [argumentos de salida]=fun(argumentos de entrada)

Page 19: 02-Introduccion Al Matlab y Scilab

19

Es conveniente que el fichero que contenga la función se llame como ella; así, la función anterior debería guardarse en el fichero fun.m; por ejemplo, si se desea programar una función que calcule, mediante el algoritmo de Euclides, el máximo común divisor de dos números naturales, basta escribir un fichero euclides.m cuyo contenido sea: function m=euclides(a,b) % Cálculo del máximo común divisor de dos números 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 instrucción >>mcd=euclides(33,121) en la variable mcd se almacenará el valor 11. Las variables de una función son siempre locales. Por tanto, aunque en el seno de la función se modifiquen los argumentos de entrada, el valor de las variables correspondientes queda inalterado. Por ejemplo, en la función 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, además, 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). Después se analiza el procedimiento que sigue MATLAB para obtener los ceros y los polos de B(s)/A(s). Considérese la función de transferencia B(s)/A(s):

𝐵𝐵(𝑠𝑠)𝐴𝐴(𝑠𝑠) =

𝑛𝑛𝑛𝑛𝑛𝑛𝑑𝑑𝑑𝑑𝑛𝑛

=𝑏𝑏0𝑠𝑠𝑛𝑛 + 𝑏𝑏1𝑠𝑠𝑛𝑛−1 + ⋯+ 𝑏𝑏𝑛𝑛𝑠𝑠𝑛𝑛 + 𝑎𝑎1𝑠𝑠𝑛𝑛−1 + ⋯+ 𝑎𝑎𝑛𝑛

Donde algunos ai y bi pueden ser cero. En MATLAB, los vectores fila num y den especifican los coeficientes del numerador y del denominador en la función de transferencia. Es decir,

𝑛𝑛𝑛𝑛𝑛𝑛 = [𝑏𝑏0 𝑏𝑏1 … 𝑏𝑏𝑛𝑛] 𝑑𝑑𝑑𝑑𝑛𝑛 = [1 𝑎𝑎1 … 𝑎𝑎𝑛𝑛]

Page 20: 02-Introduccion Al Matlab y Scilab

20

El comando [𝑟𝑟,𝑝𝑝,𝑘𝑘] = 𝑟𝑟𝑑𝑑𝑠𝑠𝑟𝑟𝑑𝑑𝑛𝑛𝑑𝑑(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛)

encuentra los residuos (r), los polos (p) y los términos 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)𝑠𝑠 − 𝑝𝑝(1) +

𝑟𝑟(2)𝑠𝑠 − 𝑝𝑝(2) + ⋯+

𝑟𝑟(𝑛𝑛)𝑠𝑠 − 𝑝𝑝(𝑛𝑛) + 𝑘𝑘(𝑠𝑠)

Ejemplo. Considere la siguiente función de transferencia:

𝐵𝐵(𝑠𝑠)𝐴𝐴(𝑠𝑠) =

2𝑠𝑠3 + 5𝑠𝑠2 + 3𝑠𝑠 + 6𝑠𝑠3 + 6𝑠𝑠2 + 11𝑠𝑠 + 6

Para esta función, 𝑛𝑛𝑛𝑛𝑛𝑛 = [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 término directo en el vector fila k). Ésta es la representación 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𝑠𝑠 + 3

+−4𝑠𝑠 + 2

+3

𝑠𝑠 + 1+ 2

La función residue también 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 están como se obtienen en el resultado de MATLAB anterior, convierte el desarrollo en fracciones simples en la razón de polinomios B(s)/A(s) del modo siguiente: >> [num,den]=residue(r,p,k); >> printsys(num,den,'s')

Page 21: 02-Introduccion Al Matlab y Scilab

21

num/den = 2 s^3 + 5 s^2 + 3 s + 6 ----------------------- s^3 + 6 s^2 + 11 s + 6 La función

𝑝𝑝𝑟𝑟𝑟𝑟𝑛𝑛𝑝𝑝𝑠𝑠𝑝𝑝𝑠𝑠(𝑛𝑛𝑛𝑛𝑛𝑛, 𝑑𝑑𝑑𝑑𝑛𝑛,′ 𝑠𝑠′) imprime num/den en términos del cociente de los polinomios en s. Ejemplo. Obtenga el desarrollo B(s)/A(s) siguiente en fracciones simples utilizando MATLAB.

𝐵𝐵(𝑠𝑠)𝐴𝐴(𝑠𝑠) =

𝑠𝑠2 + 2𝑠𝑠 + 3(𝑠𝑠 + 1)3 =

𝑠𝑠2 + 2𝑠𝑠 + 3𝑠𝑠3 + 3𝑠𝑠2 + 3𝑠𝑠 + 1

Para esta función, se tiene 𝑛𝑛𝑛𝑛𝑛𝑛 = [0 1 2 3] 𝑑𝑑𝑑𝑑𝑛𝑛 = [1 3 3 1]

La orden [𝑟𝑟,𝑝𝑝,𝑘𝑘] = 𝑟𝑟𝑑𝑑𝑠𝑠𝑟𝑟𝑑𝑑𝑛𝑛𝑑𝑑(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛)

Proporciona el resultado que se muestra a continuación. Es la representación en MATLAB del desarrollo en fracciones simples de B(s)/A(s):

𝐵𝐵(𝑠𝑠)𝐴𝐴(𝑠𝑠) =

1𝑠𝑠 + 1

+0

(𝑠𝑠 + 1)2 +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 término directo k es cero. Para obtener la función original B(s)/A(s) a partir de r, p, y k se introducen las siguientes líneas:

[𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛] = 𝑟𝑟𝑑𝑑𝑠𝑠𝑟𝑟𝑑𝑑𝑛𝑛𝑑𝑑(𝑟𝑟,𝑝𝑝,𝑘𝑘); 𝑝𝑝𝑟𝑟𝑟𝑟𝑛𝑛𝑝𝑝𝑠𝑠𝑝𝑝𝑠𝑠(𝑛𝑛𝑛𝑛𝑛𝑛, 𝑑𝑑𝑑𝑑𝑛𝑛,′ 𝑠𝑠′)

Entonces se mostrará el num/den siguiente: >> [num,den]=residue(r,p,k); >> printsys(num,den,'s')

Page 22: 02-Introduccion Al Matlab y Scilab

22

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 función

[𝑧𝑧,𝑝𝑝,𝑘𝑘] = 𝑝𝑝𝑡𝑡2𝑧𝑧𝑝𝑝(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛) para obtener los ceros, polos y ganancia k de B(s)/A(s). Considérese 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 están en s=0, -6, -4 y -2. La ganancia k es 4. Si los ceros, los polos y la ganancia k están 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

Page 23: 02-Introduccion Al Matlab y Scilab

23

OBTENCIÓN DE FUNCIONES DE TRANSFERENCIA EN CASCADA, EN PARALELO Y REALIMENTADAS (EN LAZO CERRADO) UTILIZANDO MATLAB En el análisis 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). Supóngase que hay dos componentes G1(s) y G2(s) conectadas de diferentes formas como se muestra en la figura 1, donde

𝐺𝐺1(𝑠𝑠) =𝑛𝑛𝑛𝑛𝑛𝑛1𝑑𝑑𝑑𝑑𝑛𝑛1

, 𝐺𝐺2(𝑠𝑠) =𝑛𝑛𝑛𝑛𝑛𝑛2𝑑𝑑𝑑𝑑𝑛𝑛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

𝐺𝐺1(𝑠𝑠) =10

𝑠𝑠2 + 2𝑠𝑠 + 10=𝑛𝑛𝑛𝑛𝑛𝑛1𝑑𝑑𝑑𝑑𝑛𝑛1

, 𝐺𝐺2(𝑠𝑠) =5

𝑠𝑠 + 5=𝑛𝑛𝑛𝑛𝑛𝑛2𝑑𝑑𝑑𝑑𝑛𝑛2

El programa 4 en MATLAB calcula C(s)/R(s) = num/den para cada situación de G1(s) y G2

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

(s). Obsérvese que la instrucción printsys(num,den) muestra el num/den [esto es, la función C(s)/R(s)] del sistema considerado.

Page 24: 02-Introduccion Al Matlab y Scilab

24

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 ANÁLISIS DE LA RESPUESTA TRANSITORIA CON MATLAB El procedimiento práctico para dibujar las curvas de respuesta temporal de sistemas de orden mayor que segundo es mediante simulación con computador. En esta sección se presenta el enfoque computacional para el análisis de la respuesta transitoria con MATLAB. En particular se discute la respuesta escalón, impulso, rampa y las respuestas a otras entradas simples. La función de transferencia de un sistema se representa mediante dos arrays de números. Considérese 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 representación alternativa es 𝑛𝑛𝑛𝑛𝑛𝑛 = [0 2 25] 𝑑𝑑𝑑𝑑𝑛𝑛 = [1 4 25]

Si se conocen num y den (el numerador y denominador de la función de transferencia en lazo cerrado), instrucciones del tipo

Page 25: 02-Introduccion Al Matlab y Scilab

25

𝑠𝑠𝑝𝑝𝑑𝑑𝑝𝑝(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛), 𝑠𝑠𝑝𝑝𝑑𝑑𝑝𝑝(𝑛𝑛𝑛𝑛𝑛𝑛, 𝑑𝑑𝑑𝑑𝑛𝑛, 𝑝𝑝) generarán gráficas de respuestas escalón unitario. (En el comando step, t es el tiempo especificado por el usuario.). Obsérvese que el comando step (sys) se puede utilizar para obtener la respuesta escalón unitario de un sistema. Primero se define el sistema mediante

𝑠𝑠𝑝𝑝𝑠𝑠 = 𝑝𝑝𝑡𝑡(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛) Entonces, para obtener, por ejemplo, la respuesta escalón unitario, se introduce

𝑠𝑠𝑝𝑝𝑑𝑑𝑝𝑝(𝑠𝑠𝑝𝑝𝑠𝑠) en el computador. Cuando los comandos step tienen argumentos en el lado izquierdo, como en

[𝑝𝑝, 𝑥𝑥, 𝑝𝑝] = 𝑠𝑠𝑝𝑝𝑑𝑑𝑝𝑝(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛, 𝑝𝑝) no aparece una gráfica 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 cálculo 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 gráficas: Para escribir texto en la pantalla de las gráficas, 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 gráfica es utilizar el comando gtext. La sintaxis es

𝑔𝑔𝑝𝑝𝑑𝑑𝑥𝑥𝑝𝑝(′𝑝𝑝𝑑𝑑𝑥𝑥𝑝𝑝′) Cuando se ejecuta gtext, el computador espera hasta que el cursor se posiciona (utilizando el ratón) la pantalla en la posición deseada. Cuando se pulsa el botón izquierdo del ratón, el texto encerrado en comillas simples se escribe en el dibujo en la posición señalada por el cursor. Se puede utilizar cualquier número de comandos gtext en una gráfica. Ejemplos: Se tiene la siguiente función de transferencia.

𝐶𝐶(𝑠𝑠)𝑅𝑅(𝑠𝑠)

=25

𝑠𝑠2 + 4𝑠𝑠 + 25

>>num=[0 0 25]; >> den=[1 4 25]; >> step(num,den) %Respuesta al escalón unitario >> title('Respuesta escalón unitario de G(s)=25/(s^2+4s+25)') >> grid

Page 26: 02-Introduccion Al Matlab y Scilab

26

Figura 13. Respuesta al escalón unitario.

Para la función 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 función de transferencia a analizar es:

𝐶𝐶(𝑠𝑠)𝑅𝑅(𝑠𝑠) =

1𝑠𝑠2 + 𝑠𝑠 + 1

Y la entrada R(s) es:

𝑅𝑅(𝑠𝑠) =1𝑠𝑠2

Para la utilización del comando step, la función de transferencia original se multiplica por un integrador, de tal forma que:

𝐶𝐶(𝑠𝑠) =1

(𝑠𝑠2 + 𝑠𝑠 + 1)𝑠𝑠∗

1𝑠𝑠

Por lo tanto: >> num=[0 0 0 1]; >> den=[1 1 1 0];

0 0.5 1 1.5 2 2.5 30

0.2

0.4

0.6

0.8

1

1.2

1.4Respuesta escalón unitario de G(s)=25/(s2+4s+25)

Time (sec)

Ampl

itude

Page 27: 02-Introduccion Al Matlab y Scilab

27

>> t=0:0.1:7; %Puntos de tiempo de cálculo >> 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')

Figura 14. Respuesta al Impulso Unitario.

Descripción en MATLAB de un sistema estándar de segundo orden: El sistema de segundo orden

𝐺𝐺(𝑠𝑠) =𝜔𝜔𝑛𝑛2

𝑠𝑠2 + 2𝜉𝜉𝜔𝜔𝑛𝑛𝑠𝑠 + 𝜔𝜔𝑛𝑛2

se denomina sistema de segundo orden estándar. Dadas ωn𝑝𝑝𝑟𝑟𝑟𝑟𝑛𝑛𝑝𝑝𝑠𝑠𝑝𝑝𝑠𝑠(𝑛𝑛𝑛𝑛𝑛𝑛,𝑑𝑑𝑑𝑑𝑛𝑛) o 𝑝𝑝𝑟𝑟𝑟𝑟𝑛𝑛𝑝𝑝𝑠𝑠𝑝𝑝𝑠𝑠(𝑛𝑛𝑛𝑛𝑛𝑛, 𝑑𝑑𝑑𝑑𝑛𝑛, 𝑠𝑠)

imprime num/den como un cociente de polinomios en s. Considérese, por ejemplo, el caso en el que ω

y ξ, el comando

n

0 10 20 30 40 50 60-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1Respuesta impuso unitario de G(s)=1/(s2+0.2s+1)

Time (sec)

Ampl

itude

= 5rad/seg y ξ = 0.4. El programa genera el sistema estándar de segundo orden así: >> wn=5; >> damping_ratio=0.4; >> [num0,den]=ord2(wn,damping_ratio); >> num=5^2*num0;

Page 28: 02-Introduccion Al Matlab y Scilab

28

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

Figura 15. Respuesta Rampa Unitaria.

Obtención de la respuesta escalón unitario de un sistema dado como función de transferencia: Considere la respuesta escalón unitario del sistema dado por

𝐺𝐺(𝑠𝑠) =25

𝑠𝑠2 + 4𝑠𝑠 + 25

El programa produce la gráfica de la respuesta escalón unitario de este sistema, así: %----------Respuesta a un escalón unitario---------- %*****Introduzca el numerador y el denominador de la función %de transferencia***** num=[0 0 25]; den=[1 4 25]; %*****Introduzca la siguiente orden de respuesta escalón***** step(num,den) %*****Introduzca grid y el título de la gráfica***** grid title('Respuesta a un escalón unitario de G(s)=25/(s^2+4s+25)')

0 1 2 3 4 5 6 70

1

2

3

4

5

6

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

tseg

Ent

rada

y S

alid

a

Page 29: 02-Introduccion Al Matlab y Scilab

29

Figura 16. Respuesta al Escalón 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)

Figura 17. Mapa de Polos y Ceros.

0 0.5 1 1.5 2 2.5 30

0.2

0.4

0.6

0.8

1

1.2

1.4Respuesta a un escalón unitario de G(s)=25/(s2+4s+25)

Time (sec)

Ampl

itude

-12 -10 -8 -6 -4 -2 0-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1Pole-Zero Map

Real Axis

Imag

inar

y Ax

is

Page 30: 02-Introduccion Al Matlab y Scilab

30

LUGAR GEOMÉTRICO DE LAS RAICES La gráfica del lugar geométrico de las raíces de un sistema se obtiene con el comando rlocus. >> numc=[0 6 7]; >> denc=[12 9 13]; >> rlocus(numc,denc)

Figura 18. Lugar Geométrico de las Raíces.

RESPUESTA EN FRECUENCIA Las trazas de bode se generan con el comando bode. >> bode(funtran)

Figura 19. Diagramas de Bode.

-5 -4 -3 -2 -1 0 1-1.5

-1

-0.5

0

0.5

1

1.5Root Locus

Real Axis

Imag

inar

y Ax

is

-60

-40

-20

0

20

Mag

nitu

de (d

B)

10-1

100

101

102

103

-135

-90

-45

0

Phas

e (d

eg)

Bode Diagram

Frequency (rad/sec)

Page 31: 02-Introduccion Al Matlab y Scilab

31

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

Figura 20. Márgenes de ganancia y fase.

INTRODUCCIÓN AL SIMULINK DE MATLAB Simulink es un programa con entorno gráfico para modelación y simulación. Las diferentes librerías que posee, permiten representar sistemas dinámicos de una manera muy simple. Para invocar el Simulink, basta escribir desde el comand window. >> simulink Simulink tiene dos fases de utilización: la definición del modelo a trabajar y el análisis del mismo. Para la definición del modelo, Simulink dispone de diferentes librerías. Cada una de ellas dispone de una serie de elementos que nos permiten crear y editar los diagramas de bloques utilizando el ratón. A continuación se mencionan algunas de las librerías más importantes y algunos de los bloques que se encuentran dentro de ellas. Continuos: Integradores, derivadores, función de transferencia, retardo de transporte, memorias, etc. Discretos: Funciones de transferencia discretas, filtros digitales, ZOH, espacio de estado discreto, etc. Matemática: Sumadores, ganancias funciones trigonométricas, matrices, etc. Fuentes: Escalón unitario, seno, ruido blanco, variables desde un archivo .mat, generadores de señales, etc. No-lineales: Switches, relés, saturadores, etc. Señales y sistemas: Entradas y salidas, multiplexores, demultiplexores.

-60

-40

-20

0

20

Mag

nitu

de (d

B)

10-1

100

101

102

103

-135

-90

-45

0

Phas

e (d

eg)

Bode DiagramGm = Inf , Pm = 107 deg (at 2.24 rad/sec)

Frequency (rad/sec)

Page 32: 02-Introduccion Al Matlab y Scilab

32

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, después se colocan los bloques necesarios en la ventana que se creó, arrastrando con el ratón los bloques deseados hasta el área de trabajo. Luego se procede a conectarlos por medio de un clic sostenido uniendo sus entradas y salidas. Después se configuran los parámetros de cada bloque según el modelo y posteriormente se trabaja en el menú de simulación con parámetros de cada tiempo de inicio, tiempo de finalización, etc. Después, se inicia la simulación (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 utilización de este paquete se muestra a continuación. Sea la función de transferencia en lazo abierto:

𝐺𝐺(𝑠𝑠) =𝑠𝑠 + 1

𝑠𝑠2 + 3𝑠𝑠 + 5

La respuesta al escalón 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 escalón en lazo cerrado (con realimentación unitaria).

Figura 22. Lazo Cerrado.

Simulink es una herramienta muy útil para simulación de modelos sencillos como los mostrados en los ejemplos, pero también permite la creación de modelos más complejos ya sean estos continuos o discretos, multivariables y no lineales entre otros, ya que dispone de una serie de librerías especializadas y ayudas de programación para los casos más elaborados. ACTIVIDADES

1. Sea G y H dos funciones de transferencia que modelan el comportamiento de un sistema donde: 𝐺𝐺(𝑠𝑠) = 𝑠𝑠

𝑠𝑠(4𝑠𝑠2+2𝑠𝑠+5) y 𝐻𝐻(𝑠𝑠) = 2.6𝑠𝑠+0.02

𝑠𝑠+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).

Page 33: 02-Introduccion Al Matlab y Scilab

33

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 escalón unitario y rampa unitaria.

Figura 24. Diagrama en Simulink.

Page 34: 02-Introduccion Al Matlab y Scilab

34

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 block-diagram based simulation tool similar to Simulink and LabVIEW Simulation Module.

Page 35: 02-Introduccion Al Matlab y Scilab

35

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 [email protected]. 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).

Page 36: 02-Introduccion Al Matlab y Scilab

36

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.

Page 37: 02-Introduccion Al Matlab y Scilab

37

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.

Page 38: 02-Introduccion Al Matlab y Scilab

38

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

Page 39: 02-Introduccion Al Matlab y Scilab

39

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

Page 40: 02-Introduccion Al Matlab y Scilab

40

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.

Page 41: 02-Introduccion Al Matlab y Scilab

41

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.

Page 42: 02-Introduccion Al Matlab y Scilab

42

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

Page 43: 02-Introduccion Al Matlab y Scilab

43

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.

r=[0:0.2:1]

Creating and displaying the matrix A Create a row vector with first element 0, last element 1 and increment (step size) 0.2:

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]

Page 44: 02-Introduccion Al Matlab y Scilab

44

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

Page 45: 02-Introduccion Al Matlab y Scilab

45

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.

Page 46: 02-Introduccion Al Matlab y Scilab

46

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

Page 47: 02-Introduccion Al Matlab y Scilab

47

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).

Page 48: 02-Introduccion Al Matlab y Scilab

48

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:

Page 49: 02-Introduccion Al Matlab y Scilab

49

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

Page 50: 02-Introduccion Al Matlab y Scilab

50

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

Page 51: 02-Introduccion Al Matlab y Scilab

51

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

Page 52: 02-Introduccion Al Matlab y Scilab

52

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

Page 53: 02-Introduccion Al Matlab y Scilab

53

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.

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

Bode plots of discrete-time transfer function

Page 54: 02-Introduccion Al Matlab y Scilab

54

frequency is fs [samples/sec], the actual (non-normalized) frequency is found by multiplying the normalized frequency by fs

.

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

Page 55: 02-Introduccion Al Matlab y Scilab

55

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

Page 56: 02-Introduccion Al Matlab y Scilab

56

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).

Page 57: 02-Introduccion Al Matlab y Scilab

57

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

Page 58: 02-Introduccion Al Matlab y Scilab

58

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

Page 59: 02-Introduccion Al Matlab y Scilab

59

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

Page 60: 02-Introduccion Al Matlab y Scilab

60

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 = sum0inf

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 [

[x'(k)*Q*x(k) + u'(k)*R*u(k))

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).

Page 61: 02-Introduccion Al Matlab y Scilab

61

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 [email protected]. 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.

Page 62: 02-Introduccion Al Matlab y Scilab

62

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.

Page 63: 02-Introduccion Al Matlab y Scilab

63

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.

Page 64: 02-Introduccion Al Matlab y Scilab

64

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).

Page 65: 02-Introduccion Al Matlab y Scilab

65

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:

Page 66: 02-Introduccion Al Matlab y Scilab

66

• 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.

The Sinks palette Comments to selected blocks in the Sinks palette:

• 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:

Page 67: 02-Introduccion Al Matlab y Scilab

67

• Sum (block) can be used to sum and/or subtract signals. The block is configured by double-clicking the block.

The Linear palette Comments to selected blocks in the Linear palette:

• 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:

Page 68: 02-Introduccion Al Matlab y Scilab

68

• Mathematical Expression is used to implement any Scilab function (you type the expression in the dialog box of the block).

The Nonlinear palette Comments to selected blocks in the Nonlinear palette:

• Product implements multiplication or division. It takes any number of inputs. • Interp implements interpolation or table lookup between tabular data.

The Others palette:

Page 69: 02-Introduccion Al Matlab y Scilab

69

• Text is used to add annotations (any text) to the block diagram.

The Others palette Comments to selected block on the Others palette:

• End can be used to stop the simulation at a specific simulation time. The Branching palette:

Page 70: 02-Introduccion Al Matlab y Scilab

70

• 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.

The Branching palette Comments to a selected block on the Branching palette:

• 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.

Page 71: 02-Introduccion Al Matlab y Scilab

71

• The liquid density is the same in the inlet, in the outlet, and in the tank.

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 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:

qin(t) = Ku• 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):

u(t)

qout(t) = Kvsqrt[ρ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 = ρqin(t) - ρqout(t)] (1) or, using the above relations,

d[ρAh(t)]/dt = ρKuu(t) - ρKvsqrt[ρ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)*{Kuu(t) - Kvsqrt[ρgh(t)]} (3)

Page 72: 02-Introduccion Al Matlab y Scilab

72

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 hinit

. 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.

Page 73: 02-Introduccion Al Matlab y Scilab

73

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.

Page 74: 02-Introduccion Al Matlab y Scilab

74

The simulated pump control signal u

Page 75: 02-Introduccion Al Matlab y Scilab

75

The response in the level h and the level alarm values h_AL = 0.1 m and h_AH = 0.9 m

4.3 Studying the simulator Setting up the simulator

Open the Simulate / Setup menu. This opens the dialog window shown in the figure below.

The dialog window opened with the Simulate / Setup menu.

Page 76: 02-Introduccion Al Matlab y Scilab

76

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 time-dependent 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]

Page 77: 02-Introduccion Al Matlab y Scilab

77

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 o Edit menu o Format menu o 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