Introducción Rápida A Matlab Y Simulink - Manuel Gil Rodríguez PDF
Introducción Rápida A Matlab Y Simulink - Manuel Gil Rodríguez PDF
net
www.fullengineeringbook.net
INTRODUCCIN RPIDA
A MATLAB Y SIMULINK
PARA CIENCIA E INGENIERA
www.fullengineeringbook.net
www.fullengineeringbook.net
MANUEL GIL RODRGUEZ
Cientfico Titular del Consejo Superior
de Investigaciones Cientficas (CSIC)
INTRODUCCIN RPIDA
A MATLAB Y SIMULINK
PARA CIENCIA E INGENIERA
www.fullengineeringbook.net
Manuel Gil Rodrguez, 2003
www.fullengineeringbook.net
Reservados todos los derechos.
E-mail: [email protected]
Internet://http:www.diazdesantos.es/ediciones
ISBN: 84-7978-596-9
Depsito legal: M. 43.971-2003
Presentacin ........................................................................................... XI
VII
VIII NDICE
6. SIMULINK ...................................................................................... 81
6.1. Introduccin a Simulink ......................................................... 81
6.2. Construccin de un modelo muy sencillo .............................. 85
6.3. Solucin Simulink de una ecuacin diferencial ..................... 86
6.4. Simulacin dinmica de un ecualizador ................................ 88
BIBLIOGRAFA ..................................................................................... 93
www.fullengineeringbook.net
www.fullengineeringbook.net
Presentacin
XI
www.fullengineeringbook.net
1
Primeros pasos en MatLab
1.1. INTRODUCCIN
MatLab, desde las primeras versiones dispuso de help y demo, para ini-
ciacin rpida. La informacin suministrada a travs de los mens de estas ayu-
www.fullengineeringbook.net
das, correspondientes a las ltimas versiones, crecieron de forma exponen-
cial, siendo de utilidad prctica disponer de un libro resumen de MatLab, en
donde se encuentren los comandos de uso ms frecuente, a la vez que se mues-
tren sus aplicaciones prcticas en ejercicios, desde lo ms sencillo, hasta otros
de mayor complejidad.
Este Captulo es adecuado para principiantes absolutos, y de afianzamiento
a los ya iniciados.
1.2. COMENZANDO
Al arrancar MatLab, presenta una pantalla dividida en varias ventanas,
configurables desde Desktop Layout del menu de View; en una de las ven-
tanas estar el cursor parpadeando a la derecha de >>, es la ventana de co-
mandos desde donde se ejecutan los mismos, las otras son informativas:
>> 3 + 4
ans =
7
>> 3*5
ans =
15
>> 15/3
ans =
5
1
2 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
>> 15\3
ans =
0.2000
>> 23
ans =
8
>> sin(2*pi*30/360)
ans =
0.5000
www.fullengineeringbook.net
>> A = 2*t; B = 2;
>> who
t A B
>> whos
>> what
www.fullengineeringbook.net
AjusNL
AjusN1Fun
Datos
Ecudif
EcudifP
Fun
MAT-files in the current directory D:\MatLab\work
Datos
MDL-files in the current directory D:\MatLab\work
Bcont Bfuntab BnoLineal Bsesis
Bfuentes Bmat Bsalidas Ecu2
1.4. VARIABLES
En MatLab no es necesario hacer declaraciones previas acerca de las va-
riables. El contenido de las variables de caracteres ha de ir delimitado por el
signo '.
>> numero_de_visitantes = 25
numero_de_visitantes =
25
4 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
ans =
1 1
ans =
1 4
iskeyword
ans =
'break'
'case'
'catch'
'continue'
'else'
'elseif'
'end'
'for'
'function'
'global'
'if'
'otherwise'
'persistent'
'return'
'swirch'
'try'
'while'
PRIMEROS PASOS EN MATLAB 5
>> if = 5
??? if = 5
Los nombres de las variables pueden ser tan extensos como se quiera, pero
MatLab slo reconoce los 31 primeros caracteres.
Las variables se eliminan del espacio de trabajo con el comando clear:
Spacing:
FORMAT COMPACT Suppress extra line-feeds.
FORMAT LOOSE Puts the extra line-feeds back in.
6 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
ans =
1.4142
ans =
1.41421356237310
www.fullengineeringbook.net
>> format Long e
>> sqrt (2)
ans =
1.41421356237310e+00
ans =
1. 0e+04 *
1.0000 0.0000
A =
10000 0.0001
>> format rat
>> A
A =
10000 1/10000
PRIMEROS PASOS EN MATLAB 7
1.6. PROGRAMAS
x =
1.7. FUNCIONES
El otro tipo de archivos utilizado por MatLab son las funciones, cuya pri-
mera caracterstica es que sus variables son locales en su entorno y no definidas
en el espacio de trabajo, ni en otras funciones.
Buena parte de la potencia de MatLab se basa en su extenso conjunto de
funciones, las bsicas y las distribuidas de forma separada para aplicaciones es-
pecficas, MatLab toolboxes, y otras que desarrollan los usuarios.
Las funciones toman unas variables de entrada para calcular unos datos de
salida, sea:
1 1
Fun( x ) = + 5
( x 1) + 0,1 ( x 3)2 + 0, 2
2
www.fullengineeringbook.net
Para evaluar Fun grficamente, se lanza con las siguientes instrucciones:
>> x=2:0.01:6; % Vector de 2 a 6, a incrementos de 0,01.
>> y=Fun(x); % Guardando el vector Fun(x) en y.
>> plot(x,y),grid % Representacin con rejilla.
6
2 1 0 1 2 3 4 5 6
www.fullengineeringbook.net
1.7.1. Reglas de construccin de funciones
F =
@Fun
>> feval(F,2)
ans =
-3.2576
www.fullengineeringbook.net
-3.2576
>> Fun(2)
ans =
-3.2576
>> F(2)=@cos % Creacin directa de F(2).
F =
@Fun @cos
ans =
25
a =
0 + 1. 0000i
>> conj(a)
ans =
0 1.0000i
>> sqrt(a)
ans =
0.7071 +0.7071i
>> exp(2i)
www.fullengineeringbook.net
ans =
-0.4161 + 0.9093i
>> A = (3 + 4i)*(2 j)
A =
>> r = real(A)
r =
10
>> I = imag(A)
I =
5
>> r = abs(A)
r =
11.1803
Angulo =
0.4636
0.4636
>> Aa = r*exp(Angulo*i)
Aa =
10.0000 + 5.0000i
>> t = [3 5 7, 8, 9]
t =
www.fullengineeringbook.net
3 5 7 8 9
x =
x =
0 1 2 3 4
a =
0 1 2 3 4
0 1 4 9 16
>> A = a' % Crear la matriz A, transpues-
% ta de a.
A =
0 0
1 1
2 4
3 9
4 16
B = [A; 5 25] % Aadir una lnea a una ma-
% triz.
B =
0 0
1 1
2 4
3 9
4 16
www.fullengineeringbook.net
5 25
ans =
7 12
18 31
>> A.2
ans =
1 4
9 25
>> 1../A
ans =
1.0000 0.5000
0.3333 0.2000
>> det(A)
ans =
www.fullengineeringbook.net
-1
>> inv(A)
ans =
-5.0000 2.0000
3.0000 -1.0000
y =
4 9 16
1. 10. POLINOMIOS
>> C = [1 -5 6];
>> r = roots(C)
r =
3
2
es decir, 10x 20
18 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
ans =
>> polyint(p2,2)
ans =
Equivalente a:
1 3 5 3
x x + 4x + 2
3 2
www.fullengineeringbook.net
1.10.5. Interpolacin polinomial
y5 =
26
y5c =
24.8750
y5s =
25
PRIMEROS PASOS EN MATLAB 19
1.11. matlabpath
1. 12. lookfor
1.13. LATEX
>> syms x
>> A = taylor(exp(x))
A =
1 - x + 1/2*x2 - 1/6*x3 + 1/24*x4 - 1/120*x5
>> pretty(A)
2 3 4 5
1 - x + 1/2 x - 1/6 x + 1/24 x - 1/120 x
>> latex(A)
ans =
1 - x + 1/2\,{x}{2}-1/6\,{x}{3}+1/24\,{x}{4}-
{\frac{1}{120}}\,
{X}^{5}
20 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
Tiempo =
1.0*e + 03 *
2.0030 0.0010 0.0290 0.0160 0.0400 0.0502
ans =
www.fullengineeringbook.net
7.3161e + 05
29-Jan-2003
2003 1 29 0 0 0
>> datenum(date)
7.3161e + 05
>> date
ans =
29-Jan-2003
elapsed_time =
3.6174
Tt =
3.6642
ans =
www.fullengineeringbook.net
-1.2835e + 03
>> clear
>> X=rand(2,3)
X =
>> Y=round(X)
Y =
0 0 0
0 1 1
22 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
X Y
>> X
X =
>> Y
Y =
0 0 0
0 1 1
www.fullengineeringbook.net
>> A=[1.5 2.49; 0.2 9.99]
A =
1.5 2.49
0.2 9.99
>> ceil(A)
ans =
2 3
1 10
>> floor(A)
ans =
1 2
0 9
www.fullengineeringbook.net
www.fullengineeringbook.net
2
Clculo simblico
2.1. INTRODUCCIN
x =
x
25
26 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
www.fullengineeringbook.net
M =
(a-b)/(c+d)
>> pretty(M)
a - b
c + d
80
70
60
50
40
30
20
10
10
3 2 1 0 1 2 3
t
www.fullengineeringbook.net
>> y
Y=
2*15^(1/2)/5*sin(15^(1/2)/2*t)*exp(-3/2*t)
>> dy=diff(y);
>> dy=simplify(dy);
>> dy=factor(dy);
>> pretty(dy)
Intdy =
2/5*15^(1/2)*sin(1/2*15^(1/2)*t)*exp(-3/2*t)
28 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
60
40
20
20
40
60
80
100
3 2 1 0 1 2 3
t
www.fullengineeringbook.net x+ y= 5
x y = 1
ezx = 7,389
>> syms x y z
>> [x,y,z]=solve(x+y-5,x-y+1,exp(x*z)-7.389)
x =
2
y =
3
z =
1/2*log(7389/1000)
>> z=double(z)
z =
1.0000
d2 y dy
2
+3 + 6y = 0
dt dt
www.fullengineeringbook.net
yc =
2/5*15^(1/2)*exp(-3/2*t)*sin(1/2*15^(1/2)*t)
r =
C1*exp(-t)+C2*exp(-2*t)
>> s=dsolve('D2y+3*Dy+2*y=0','Dy(0)=l,y(0)=0')
s =
exp(-t)-exp(-2*t)
>> S=dsolve('D2y+3*Dy+2*y=cos(t)','Dy(0)=l,y(0)=0')
S =
1/l0*cos(t)+3/l0*sin(t)+1/2*exp(t)-3/5*exp(-2*t)
30 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
(s) = 0 f (t) e st dt
>> syms a w t s
>> F=cos(w*t)*exp(a*t)
F =
cos(w*t)*exp(a*t)
>> L=laplace(F,t,s)
L =
(s+a)/((s+a)^2+w^2)
>> pretty(L)
www.fullengineeringbook.net
(s + a)
-----------
2 2
(s + a) + w
>> L1=laplace(exp(-t),t,s)
L1 =
1/(l+s)
>> pretty(L1)
1
----
1 + s
>> I=ilaplace(L,s,t)
I =
cos(w*t)*exp(-a*t)
>> I1=ilaplace(Ll,s,t)
I1 =
exp(-t)
CLCULO SIMBLICO 31
2.5. LMITES
>> limit(1/x,x,0,'left')
ans =
-inf
>> Lim=limit((x^3-1)/(x^2-l),x,1)
Lim =
3/2
www.fullengineeringbook.net 2
exp(-8) - exp(-8) (x - 8) + 1/2 exp(-8) (x - 8)
>> pretty(taylor(f,x,3))
2
1 - x + 1/2 x
r=maple('Sentencia Maple')
r=maple('Funcin',Argl,Arg2,...)
ans =
>> maple('laplace(y(t)=t^2+sin(t),t,s)')
ans =
laplace(y(t),t,s) = 2/s^3+1/(s^2+1)
>> M1=maple('invlaplace((s+1)/(s*(s^2+s+1)),s,t)')
M1 =
1+1/3*exp(-1/2*t)*3^(1/2)*sin(1/2*3^(1/2)*t)-exp(-1/2*t)*...
cos(1/2*3^(1/2)*t)
+ 3 y + 6y = 0
www.fullengineeringbook.net
con condiciones iniciales:
y (0) = 3
y (0) = 0
>> maple('eq:=diff(y(t),t$2)+3*diff(y(t),t)+6*y(t)=0')
ans =
eq := diff(y(t),'$'(t,2))+3*diff(y(t),t)+6*y(t) = 0
>> maple('ini:=y(0)=0,D(y)(0)=3')
ans =
>> maple('Sol:=dsolve({eq,ini},{y(t)})')
ans =
2 y 3y = 0
y (0) = 1
y (0) = 0
ans =
eq := diff(y(t),'$'(t,2))-2*diff(y(t),t)-3*y(t) = 0
>> maple('ini:=y(0)=0,D(y)(0)=1')
www.fullengineeringbook.net
ans =
>> maple('La:=laplace(eq,t,s)')
ans =
La := s*(s*laplace(y(t),t,s)-y(0))-D(y)(0)-2*s* ...
laplace(y(t),t,s)+2*y(0)-3*laplace(y(t),t,s) = 0
>> Maple('Sol:=subs(ini,{La})')
ans =
>> maple('Sol1:=solve(Sol,{laplace(y(t),t,s)})')
ans =
>> maple('Solf:=invlaplace(Sol1,s,t)')
Solf =
34 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
>> maple('simplify(Solf)')
ans =
{y(t) = -1/4*(-1+exp(-4*t))*exp(3*t)}
1
y (t ) = (e 4 t 1) e 3t
4
www.fullengineeringbook.net
3
Sentencias de control de flujo
3.1. input
>> ['Hola',R]
ans =
Hola Pepe
>> ['Hola';R]
Hola
Pepe
>> P+1
ans =
35
36 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
Operadores relacionales
eq == Igual
ne ~= No igual
lt < Menor que
gt > Mayor que
le <= Menor que o igual
ge >= Mayor que o igual
www.fullengineeringbook.net
En la primera de las siguientes instrucciones se responde con hola, ya
que es verdad que 'a' es igual a 'a'. En la segunda esto se obvia, dado que la
condicin es falsa.
>> if 'a'=='a', 'hola', end
ans =
hola
if condicin 1
Cuantas Botellas ? 8
Pu =
5.5000
Pt =
44
38 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
www.fullengineeringbook.net
>> Tabla
>> D
D =
>> Tabla1
>> D
D =
A =
3.5. continue
www.fullengineeringbook.net
3.6. break
6 5
4 >> subplot(221)
>> fplot(Fun,[pi pi]) >> subplot(222)
2 >> stairs(x,Fun(x),*)
0 0
6 5
2 0 2 2 0 2
5 5 1
>> subplot(223)
>> plot(x,Fun(x),:.)
0 0 0
5 5 1
2 0 2 4 2 0 2 4
0 0
5 6
2 0 2 2 0 2
5 90 0,5
>> subplot(223) 120
0,4 60
>>stem(x,Fun(x))
0,3
150 0,2 30
0 180 0
210 330
240 300
5 270
2 0 2
>> x=-pi:.25:pi;
>> subplot(221), fplot('fun',[-pi pi])
>> axis([-pi pi -6 6])
>> subplot(222), stairs(x,fun(x),*-)
>> axis([-pi pi -5 5])
>> subplot(223), plot(x,fun(x),':.')
>> axis([-pi pi -5 5])
>> subplot(224), plotyy(x,fun(x),x,x.^2)
>> subplot(221), bar(x,fun(x),0.2)
>> axis([-pi pi -5 5])
>> e=rand(length(x),1)
>> subplot(222), errorbar(x,fun(x),e)
>> axis([-pi pi -6 6])
>> subplot(223), stem(x,fun(x))
>> axis([-pi pi -5 5])
>> subplot(224), polar(x,sin(2*x).*cos(2*x))
www.fullengineeringbook.net
>> plotmatrix(x,A,'h-')
2
0
2
4
1
Seno de X
Seno de X
0,5
0,5
20
Tangente de X
0
20
3 2 1 0 1 2 3 4
Eje de las X
35
30
25
20
15
10
0
1
0,5 1
0 0,5
0
0,5 0,5
1 1
6% a=[1 3 5 7]
pie(a,a==a(2))
19%
44%
31%
Figura 4.5. Grfico en tarta.
2
y= sin(x) e - x
y=sin(x) e - x
5
10 8 6 4 2 0 2 4 6 8 10
Eje de las X
Distancia m
4.4. LAPRINT
www.fullengineeringbook.net
Al incluir cuadros grficos procedentes de MatLab, en textos LATEX, es-
calados ya con resizebox o scalebox, suele haber recortes indeseados y
desproporcin en los textos de los cuadros grficos en los documentos finales.
6
4
2
0
2
4
6
1
2
3
4 8
5 7
6 6
7 5
4
8 3
2
1
b Azul Continua
g Verde o o : Punteada
r Rojo x x Trazo-Punto
www.fullengineeringbook.net
c
m
y
Cian
Magenta
Amarillo
+
*
s
+
*
Trazo-Trazo
k Negro d
w Blanco
M
<
>
p
h
text(2,sin(2).*exp(-.25*abs(2)),...
'\fontsize{16}\leftarrow sin(t)\cdote^{-0.25\cdotabs(t)}
')
48 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
xlabel('\fontsize{l5} t')
ylabel('\fontsize{l5} sin(t)\cdote^{-0.25\cdotabs(t)}')
hold on
a=plot(t,z);
text(0.25,cos(0.25).*exp(-.25*abs(0.25)),...
'\fontsize{14}\leftarrow cos(t)\cdote^{-0.25\cdotabs(t)}
')
set(a,'LineWidth',0.5,'Color','k')
t1=-11; y1=sin(t1).*exp(-.25*abs(t1));
t2=0; y2=cos(t2).*exp(-.25*abs(t2));
line([t1 t2],[y1 y2],'LineWidth',8,'Color',[1 0 1])
1
cos(t)e0,25 abs(t)
0,8
0,6
sin(t)e 0,25abs(t)
0,4
sin(t)e 0,25 abs(t)
0,2
www.fullengineeringbook.net 0
0,2
0,4
0,6
10 5 0 5 10
t
hold of
% ------------------------------------------------------------
------
4.6. area
4 subplot(211)
area(x,Fun(x))
2
6
2 1 0 1 2 3 4 5
4
subplot(212)
2
area(x,Fun(x),5)
0
6
2 1 0 1 2 3 4 5
14%
25%
-10.0814
>> x=fminbnd(F,0,3)
x =
2.0351
ans =
3.0965
>> fzero(F,4)
ans =
3.0965
Sea el sistema:
www.fullengineeringbook.net
Sea el sistema x+y=5
x y = 1
e z x = 7, 389
x =
2.000
3.000
1.000
>>
www.fullengineeringbook.net
En este caso, se llama a la funcin a minimizar, pHAjusMin, suministran-
do a continuacin los valores iniciales de los parmetros a minimizar, siendo
opcional aadir una variable de opciones, seleccionables con optimset.
La aplicacin y funcionamiento de fminsearch se comprende fcilmen-
te con el siguiente ejemplo de ajuste de datos experimentales a una funcin,
ecuacin (5.1).
En el proceso de lodos activos, la tasa de crecimiento de los lodos es fun-
cin del pH, datos experimentales.
Las reacciones de biodegradacin, actividad microbiana, transcurren a un
pH ptimo, prximo a la neutralidad y disminuyen hasta anularse, al separarse
a zonas agresivas, como son las zonas de pHs cidos o alcalinos.
El efecto del pH en la velocidad especfica de generacin de lodos se re-
presenta adecuadamente por una funcin tipo campana:
1
( pH ) = pk1 pH (5.1)
1 + 10 + 10 pH pk2
Las constantes pk1 y pk2, se calculan por ajuste de datos, representando los
valores en los que (pH), tiene el valor de 0,5.
54 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
0,9
pk1 = 5,2036
0,8
pk2 = 10,1128
0,7
0,6
(pH)
0,5
0,4
0,3
0,2
0,1
0
0 2 4 6 8 10 12 14
pH
Figura 5.1. Ajuste de la tasa de crecimiento frente al pH.
www.fullengineeringbook.net
% --------------- pHAjus.m ----------------------------
clear,clf
global pH mu
pH=[O 1 2 3 4 5 6 7 8 9 10 11 12 13 14]';
mu=[O .01 .02 .04 .12 .4 .8 1 .96 .9 .6 .05 .01 ...
.01 0]';
pk=fminsearch('pHAjusMin',[3 10]);
plot(pH,mu,'*')
hold on
pHc=0:.1:14;
muc=1../(1+1O..(pk(1)-pHc)+10..(pHc-pk(2)));
plot(pHc,muc,'-')
mu1=1../(1+10..(pk(1)-pk(1))+10..(pk(1)-pk(2)));
mu2=1../(1+10..(pk(1)-pk(2))+10..(pk(2)-pk(2)));
line([pk(1) pk(1)],[0 mu1],'Color','k')
line([pk(2) pk(2)],[0 mu2],'Color','k')
text(1,0.85,'pk1 = '), text(2.5,.85,num2str(pk(1)))
text(1,0.75,'pk2 = '), text(2.5,.75,num2str(pk(2)))
xlabel('pH'), ylabel('\mu(pH)'), grid, hold off
%--------------------------------------------------------
global pH mu
pk1=p(1); pk2=p(2);
muc=1../(1+10..(pk1-pH)+10..(pH-pk2));
q=sum((mu-muc).2);
%--------------------------------------------------
www.fullengineeringbook.net
>>
>>
>>
x=[-pi*2:.5:pi*2]';
A=2; B=.2;
y=A*sin(x).*exp(-B*x);
>> r=rand(length(x),1)-0.5;
>> Y=y+r;
>> Opciones=optimset('Display','iter','Diagnostics','on',...
'TolX',1e-29,'TolFun',1e-29,'LargeScale','on',...
'MaxFunEvals',100)
>> est=lsqcurvefit('AjusNlFun',[0 0],x,Y,[-5 -5],[10 5],...
Opciones)
>> Ac=est(1); Bc=est(2);
>> xc=linspace(x(1),x(length(x)));
>> yc=Ac*sin(xc).*exp(-Bc*xc);
>> plot(x,y,'o'), hold on, plot(xc,yc,'-'), hold off
>> text(0,5,'A='), text(1,5,num2str(A))
>> text(0,4,'B='), text(1,4,num2str(B))
>> text(4,5,'Ac='), text(5,5,num2str(Ac))
>> text(4,4,'Bc='), text(5,4,num2str(Bc))
>> xlabel('X'), ylabel('A.sen X e{-BX}')
function F=AjusNlFun(p,x)
%---------------AjusNlFun.m---------------
A=p(1); B=p(2);
F=A*sin(x).*exp(-B*x);
%-----------------------------------------
56 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
5 A= 2 Ac=2,096
4 B=0,2 Bc=0,19176
3
Asen Xe BX
3
8 6 4 2 0 2 4 6 8
X
30
25
20 Ac=0,95551
Bc= 4,6119
Cc= 5,6322
x 2+5x+6
15
10
5
8 7 6 5 4 3 2 1 0 1 2
x
Figura 5.3. Ajuste de datos con polyfit.
APLICACIONES DE CLCULO NUMRICO 57
d2y dy
2
+3 + 6y = 0 (5.2)
dt dt
z = y'
z' = 3z 6y (5.3)
y' = z (5.4)
www.fullengineeringbook.net
>>
>>
t=sym('t');
y=('2*15(1/2)/5*sin(15(1/2)/2*t)*exp(-3/2*t)');
>> dy=diff(y);
>> subs(y,t,-pi)
ans =
34.1795
>> subs(dy,t,-pi)
ans =
276.0593
250
200
Funcin y derivada
150 y
100
50 y
50
100
3 2 1 0 1 2 3
Tiempo
www.fullengineeringbook.net
En el siguiente listado se muestra el programa de definicin de las ecua-
ciones a integrar:
function dy=Ecudif(t,y)
-------------------- Ecudif.m -----------------------------
% y''+3y'+6y=0
% es equivalente al sistema:
% z'=-3z-6y
% y'=z
%-----------------------------------------------------------
dy(1)=-3*y(1)-6*y(2); % y(1)=z
dy(2)=y(1); % y(2)=y
dy=[dy(1);dy(2)];
%-----------------------------------------------------------
d y1
= 1 (t, y1 , y2 , yn )
dt
d y2
= 2 (t, y1 , y2 , yn )
dt
d yn
= n (t, y1 , y2 , yn )
dt
pk = h (tk , yk )
qk = h tk + , yk + k
h p
2 2
www.fullengineeringbook.net rk = h tk + , yk + k
h
2
q
2
sk = h (tk + h, yk + r )
pk + 2 qk + 2 rk + sk
yk ,i+1 = yk ,i +
6
function [t,y]=odegil4(f,x,y0,h)
%-------------------------------------------------------------
-------
% [t,y]=odegil4(f,x,y0,h), resuelve ecuaciones y'=f(t,y),
% x vector en linea de la variable independiente,
% y0 vector en linea de las condiciones iniciales,
% h paso de integracin.
%-------------------------------------------------------------
-------
x=x'; t=[]; t(1)=x(1); y=y0;
APLICACIONES DE CLCULO NUMRICO 61
N=(x(length(x))-x(1))/h; Ne=length(y0);
for I=1:N
T=t(I);
Y=y(I,:);
for J=1:Ne
p=h*feval(f,T,Y');
q=h*feval(f,T+h/2,Y'+p/2);
r=h*feval(f,T+h/2,Y'+q/2);
s=h*feval(f,T+h,Y'+r);
end
t(I+1)=t(1)+h*I ;
Inc=(p+2*q+2*r+s)/6;
y(I+1,:)=y(I,:)+Inc;
end
y=spline(t,y',x);
y=[reshape(y,Ne,length(x))]';
t=x;
%-------------------------------------------------------------
www.fullengineeringbook.net
function dy=ecudif(t,y)
dy(1)=2*t;
dy(2)=3*t.2;
dy(3)=4*t.3;
dy(4)=cos(t);
dy=[dy(1);dy(2);dy(3);dy(4)];
U
Y
X
Qi V Qe
h
www.fullengineeringbook.net
Figura 5.5. Esquema general de un sistema dinmico.
h
Qe
V
Qi
H
Q = L h1,5 2 g (5.5)
0, 003 h2
= 0, 405 + 1 + 0, 55 (5.6)
h ( H + h)2
dV
= Qi Qe (5.7)
www.fullengineeringbook.net dt
V
h= H (5.8)
A
www.fullengineeringbook.net
%
% Parmetros y Estado Inicial
%---------------------------------------------------------
%
A=150; H=4; L=10; tf=20*60;
Qe1=50/3600; Qe2=100/3600; Qe3=150/3600; V=590;
%
% Integracin de la ecuacin de estado
%---------------------------------------------------------
%
Opciones=odeset('RelT',1e-7,'AbsTol',1e-7);
[t,X]=ode23('VerteX',[0,tf],V,Opciones);
%
% Clculo de las Salidas
%---------------------------------------------------------
%
Y=verteY(t,X);
%
% Representacin de resultados
%---------------------------------------------------------
%
T=t/60; tff=T(length(T));
%
subplot(311); plot(T,Y(:,1)*3600,'*-',T,Y(:,2)*3600,'o--')
axis([t0 tff -5 154]), ylabel('Cuadales (m3/h)')
%
subplot(312);plot(T,Y(:,3)*1000,'*-'),axis([t0 tff -1 14])
ylabel('Altura de Lmina (cm)')
APLICACIONES DE CLCULO NUMRICO 65
%
subplot(313); plot(T,X,'*-'), axis([t0 tff 590 603])
ylabel('Volumen del Agua (m3)'),xlabel('Tiempo (Minutos)')
%
%---------------------------------------------------------
La funcin que calcula el estado del sistema, volumen del tanque, es:
function dX=VerteX(t,X)
%--------------------- VerteX.m---------------------------
%
% Clculo del volumen del tanque
%---------------------------------------------------------
%
%
global A H L Qe1 Qe2 Qe3 tf
%
% Clculo del caudal de salida
%---------------------------------------------------------
%
Y=VerteY(t,X); U=Y(1,1);
%
% Variacin de volumen del tanque
%---------------------------------------------------------
www.fullengineeringbook.net 150
Caudales (m3 /h)
100
50
0
0 2 4 6 8 10 12 14 16 18 20
Altura de Lamina (cm)
10
0
0 2 4 6 8 10 12 14 16 18 20
Volumen del Agua (m3 )
600
595
590
0 2 4 6 8 10 12 14 16 18 20
Tiempo (Minutos)
%
dX=U-Y(1,2);
%
%---------------------------------------------------------
function Y=VerteY(t,X)
%---------------------- VerteY.m -------------------------
%
% Clculo de Caudal de Salida y Altura de Lmina
%
%---------------------------------------------------------
%
%
global A H L Qe1 Qe2 Qe3 tf
%
N=length(t);
Y=zeros(N,2);
for i=1:N
% Caudal de Entrada
if t(i)<tf/3
Y(i,1)=Qe1;
elseif t(i)<2*tf/3
Y(i,1)=Qe2;
www.fullengineeringbook.net
else
end
Y(i,1)=Qe3;
h=X(i)/A-H;
if h<=0
Y(i,2)=0; Y(i,3)=0;
else
mu=0.405+0.003/h*(1+ 0.55*h2/(h+H)2);
% Caudal de salida y altura de lmina
Y(i,2)=mu*L*h*(2*9.8*h)(1/2);
Y(i,3)=h;
end
end
%---------------------------------------------------------
[ f(t )] = es F(s)
2 s 2 6 s + 12
e s
2 s 2 + 6 s + 12
En procesos qumicos en los que ocurren tiempos muertos, como en una co-
lunma de rectificacin o retrasos hidrulicos, es ms til la aproximacin me-
nos comn:
1
e s
s + 1
n
y+ y' = x x'
2 2
2
y' = ( x y) x' (5.10)
Esta ecuacin integrada conduce a:
2
y( t ) = x ( t ) = ( x (t ) y(t )) dt x (t )
www.fullengineeringbook.net
x(t)
x(t- )
2/
d (t )
= s F( s) (0)
dt
a s b
1+0,01 s
a s = 0,01 s b + b
(
b = 100 a b dt )
www.fullengineeringbook.net
Este es un procedimiento aproximado para obtener la derivada de una fun-
cin a travs de su integral.
Para visualizacin rpida de la aproximacin del clculo de variables re-
trasadas y derivadas, se elabora un programa de demostracin en el que la fun-
cin de entrada es el tiempo al cuadrado, y la funcin retrasada, el tiempo al
cuadrado retrasado en tres unidades.
En el programa principal, RetraLan.m se definen los parmetros de ope-
racin, tiempo, retraso, condicin inicial, integrador, la representacin grfica
y la tabla de resultados numricos.
%------------------RetraLan.m ----------------------
t=0:.1:12;
global tau
tau=3;
y10=0; y20=0;
[t,y]=odegil4('Retraso',t,[y10 y20],0.01);
Y=y(:,1); Yr=y(:,2);
subplot(211),plot(t,Y), grid
axis([0 12 -2 145])
ylabel('\fontsize{12} t2')
subplot(212),plot(t,Yr), grid
70 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
axis([0 12 -3 82])
ylabel('\fontsize{12} (t-3)2')
xlabel('\fontsize{12} t)
T=t(1):t(length(t));
Yn=round(spline(t,Y,T));
Ynr=round(spline(t,Yr,T));
[T Yn Ynr]
%---------------------------------------------------
%-----------------Retraso.m ------------------------
function dy=Retraso(t,y)
global tau
F=t.2; % Funcion.
dy(1)=100*(F-y(1)); % Derivada de Funcion.
dy(2)=(y(1)-y(2))*2/tau-dy(1); % Funcion retrasada.
dy=[dy(1);dy(2)];
%---------------------------------------------------
t2 100
50
0
0 2 4 6 8 10 12
80
60
(t3)2
40
20
0
0 2 4 6 8 10 12
t
www.fullengineeringbook.net
En el programa principal se hizo uso de la funcin spline, para obtener
datos interpolados. Su sintaxis es:
Yn=spline(X,Y,Xn)
1 2 3 4 5
>> Yn=spline(X,Y,Xn)
Yn =
1 4 9 16 25
72 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
www.fullengineeringbook.net Y=mX+b
=YmXb
2 = Y 2 + m2 X 2 + N b2 2 m X Y 2 b Y + 2 m b X
d 2
= 2 m X 2 2 X Y 2 b X
dm
d 2
= 2 N b 2 Y + 2 m X
db
m X 2 + b X = X Y
m X + N b = Y
APLICACIONES DE CLCULO NUMRICO 73
Y X 2 X X Y
b= (5.12)
N X 2 ( X )2
N X Y X Y
m= (5.13)
N X 2 ( X )2
(Yc Y )2
r=
(Y Y ) 2
N X Y X Y
r= (5.14)
( N X ( X )2 ) ( N Y 2 ( Y )2 )
2
www.fullengineeringbook.net
Los datos con los que se va a trabajar se guardarn en un archivo separado,
con nombre alusivo a su contenido, formando una matriz a la que se la deno-
mina datos, en cuya primera columna estn las X, y en la segunda las Y:
%----------------- DatosAL.m -----------------------
datos=[1 6.23
2 8.58
3 10.84
4 12.48
5 13.35
6 15.81
7 18.87
8 20.83
9 21.82];
%---------------------------------------------------
SY=sum(Y);
SY2=sum(Y.2);
SXY=sum(X.*Y);
b=(SY*SX2-SX*SXY)/(N*SX2-SX2);
m=(N*SXY-SX*SY)/(N*SX2-SX2);
r=(N*SXY-SX*SY)/((N*SX2-SX2)*(N*SY2-SY2)).5;
Yc=m*X+b;
plot(X,Y,'*',X,Yc,'-')
text(1.5,15,'r='), text(2,15,num2str(r))
text(1.5,17,'b='), text(2,17,num2str(b))
text(1.5,19,'m='), text(2,19,num2str(m))
xlabel('X'), ylabel(Y)
%---------------------------------------------------
22
20
m= 1,975
18
b= 4,4372
16
r= 0,99502
www.fullengineeringbook.net
14
12
10
6
1 2 3 4 5 6 7 8 9
Las funciones no lineales con uno o dos parmetros son susceptibles de li-
nealizacin por transformaciones de variables, para lograr nuevas variables re-
lacionadas linealmente, a las que se le aplica el ajuste lineal expuesto. Este tra-
tamiento de datos tiene la ventaja de que siempre es ms fcil elucidar si una
APLICACIONES DE CLCULO NUMRICO 75
C R x (1 x )
y=x+ (5.15)
[ x + R (1 x )]2
en donde:
x Fraccin molar del componente ms voltil del lquido.
y Fraccin molar del componente ms voltil del vapor.
R Constante, que indica la posicin del mximo en la representacin y-x.
C Constante, que indica el valor del mximo en la representacin y-x.
D=yx
A=CR
x
U=
1 x
A U
D= (5.17)
(U + R)2
U
V2 =
D
76 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
R U
V= + (5.18)
A A
La ecuacin (5.18) relaciona linealmente V con U. Si la distribucin de los
datos (x,y) sometidos a las transformaciones expuestas siguen una trayectoria
lineal, indica que la ecuacin (5.15) es consistente.
De la recta obtenida se determinan su pendiente y ordenada en el origen, re-
lacionados con R y C segn:
1 1
m= =
A RC
R R
b= =
A RC
www.fullengineeringbook.net
Deshaciendo los cambios hechos, los coeficientes de el ecuacin (5.15) son:
1
C=
bm
b
R=
m
Con los valores as calculados de R y C, y los valores de x, se calculan unas
yc, que debern estar muy prximos a las y de partida.
De la bibliografa especializada se obtuvieron los datos de equilibrio iso-
brico, 760 mm de Hg. lquido-vapor de Benceno-nButanol, que se utilizan en
el programa Equilibrio.m, en donde se aplican los clculos expuestos.
%----------------- Equilibrio.m ----------------
datos=[.0064 .0201
.0087 .0285
.0098 .0318
.0103 .0495
.0111 .0568
.0152 .0666
.0198 .0778
.0208 .0939
.0250 .0984
.0331 .1295
.0488 .1898
APLICACIONES DE CLCULO NUMRICO 77
.0553 .2170
.0568 .2199
.0620 .2356
.0753 .2824
.0864 .3152
.1120 .3840
.1209 .4082
.1553 .4881
.1779 .5361
.1992 .5693
.2390 .6421
.2718 .6712
.2852 .6836
.3440 .7493
.3978 .7874
.4528 .8161
.5295 .8601
.5753 .8689];
%-----------------------------------------------
x=datos(:,1); y=datos(:,2);
D=yx; U=x./(1x); V=sqrt(U./D);
est=polyfit(U,V,1);
m=est(1); b=est(2);
subplot(221), plot(x,y,'o-')
subplot(222), plot(U,V,'o',U,m*U+b,'-')
www.fullengineeringbook.net
C=1/(b*m); R=b/m;
2
m= 1,152 R= 0,47756
b= 0,55015 C= 1,5779
V=(U/(yx))0,5
1,5
0,5
0,2 0,4 0,6 0,8 1 1,2
U=x/(1x)
0,8
0,6
y
0,4
0,2
0,05 0,1 0,15 0,2 0,25 0,3 0,35 0,4 0,45 0,5 0,55
x
yc=x+C*R*x.*(1-x)./(x+R*(1-x)).2;
subplot(212),plot(x,y,'o',x,yc,'-')
%-----------------------------------------------
www.fullengineeringbook.net
>> t=[0:0.001:0.5]';
>> size(t)
ans =
501 1
>> x=sin(2*pi*50*t)+sin(2*pi*100*t)+sin(2*pi*200*t);
y=x+3*rand(length(t),1);
Y=fft(y);
APLICACIONES DE CLCULO NUMRICO 79
5001 1
La frecuencia se forma mediante la instruccin:
>> f=1000*(1:256)/512;
>> size(f)
ans =
1 256
>> f=f';
>> size(f)
ans =
256 1
x=sin(2 pi 50 t)+sin(2 pi 100 t)+sin(2 pi 200 t)
5
y=x+3 rand(length(t),1)
2
4
1 3
www.fullengineeringbook.net 0
2
1
1 0
1
2 2
0 0,05 0,1 0 0,05 0,1
Tiempo (seg.) Tiempo (seg.)
x 10 4
7
Potencia Espectral
6
5
4
3
2
1
0
50 100 150 200 250
Frecuencia
>> xlabel('Tiempo')
>> subplot(222), plot(t(l:50),y(1:50))
>> ylabel('y=x+3rand')
>> xlabel('Tiempo')
>> subplot(212), plot(f,P(1:256))
>> axis([ 0 500 0 70000])
>> ylabel('Potencia espectral')
>> xlabel('Frecuencia')
La exactitud con que funciona MatLab es eps, cuyo valor es 2,2204 1016.
Al dividir una expresin por una variable x, que en un proceso de clculo
tomase el valor 0, provoca un warning Divide by zero. Este inconveniente
se obvia mediante:
x=x+(x==O)*eps;
www.fullengineeringbook.net
Este procedimiento nicamente cambia el valor de x, cuando su valor es 0,
asignndole el valor de eps.
Los nmeros ms grande y ms pequeo, en valor absoluto, que utiliza Mat-
Lab son realmax y realmin, de valores 1,7977 10308 y 2,2251 10308, res-
pectivamente.
Para evitar que una variable x, no exceda de un valor lmite dado de satu-
racin o rebose, X, se procede segn:
x=x.*(abs(x) < X)+X.*(abs(x)>X);
6
Simulink
www.fullengineeringbook.net
www.fullengineeringbook.net
bridos. Simulink viene con muchos ejemplos a modo de demos para facilitar su
uso.
En la Figura 6.1 se presentan los mens de las libreras que suministran con-
juntos de bloques operacionales, cuyos contenidos se muestran en las Figu-
ras 6.2, a 6.8, con los que se compondrn los modelos deseados.
SIMULINK 83
www.fullengineeringbook.net
www.fullengineeringbook.net
d2y dy
2
= 3 6 y
dt dt
Qi(t)
Ci(t)
Volumen
de seguridad
Variacin
de volumen V(t) C(t)
Volumen
inicial Q
C(t)
dV
= Qi Q (6.1)
dt
= Ci Q +
dC Qi dV C
(6.2)
dt V dt V
2
Qi (t ) = Q + Qv sin t (6.3)
T
www.fullengineeringbook.net
El volumen del lquido en el ecualizador estar dado por:
t
2 t
V = V (0) + Qv
sin
0 T
(6.4)
Qv T 2
V = V (0) + 1 cos t (6.5)
2 T
[0 2 4 6 8 10 12 14 16 18 20 22]
[211 168 155 162 220 330 460 533 475 370 290 250]
90 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
Figura 6.13. Esquema Simulink para el clculo de la evolucin del volumen contenido
en un ecualizador con caudal variable.
El bloque Mux permite conducir por una lnea varias seales. En el ejemplo,
Mux se utiliza para realizar operaciones en los bloques f(u), y para represen-
tar varias seales en un grfico.
2500
Qi
Q
www.fullengineeringbook.net 2000
Volumen
Caudales, (m3/h), Volumen (m3)
1500
1000
500
0
0 20 40 60 80 100 120
Tiempo, (Horas)
Figura 6.14. Resultado grfico del clculo de la evolucin del volumen contenido
en un ecualizador con caudal variable.
www.fullengineeringbook.net
Figura 6.15. Esquema Simulink para el clculo del volumen y composicin
de un ecualizador, con alimentacin de caudal y concentracin variables.
[0 2 4 6 8 10 12 14 16 18 20 22]
[150 130 89 109 165 195 398 413 364 270 215 174]
92 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA
450
C
Ci
400
350
Conc. Entrada/salida (mg/l)
300
250
200
150
100
www.fullengineeringbook.net 50
0 20 40 60 80 100 120 140 160 180 200
Tiempo (Horas)
Figura 6.16. Concentracin de salida del ecualizador, lnea continua,
frente a concentracin de entrada.
[1] Brian D. Hanhn. Essential MatLab for scientists and engineers. Buter-
worth-Heinemann. (2002).
[2] Brian D. Hunt. A guide to MatLab for beginners and experienced users.
Cambridge Univ. Press. (2001).
www.fullengineeringbook.net
[3] Duane Hanselman, Bruce R. Littlefield. Mastering MatLab 6. The MatLab
curriculum series. Prentice Hall. (2000).
[4] James B. Dabney; Thomas L. Harman. Mastering simulink 4 S/E. The
MatLab curriculum series. Prentice Hall. (2001).
[5] Edward B. Magrab. Engineers guide to MatLab. Prentice Hall. (2000).
[6] Rudra Pratrap. Getting starting with MatLab, Version 6: Quick introduc-
tion. Oxford University Press. (2001).
[7] Stephen J. Chapman. MatLab programming for engineers. Brooks-Cole
Pub. Co. (2001)
[8] Gil Rodrguez M. Clculos avanzados en procesos de descontaminacin de
aguas. Consejo Superior de Investigaciones Cientficas. (2003).
93
www.fullengineeringbook.net
ndice alfabtico
..., 21 continue, 40
LATEX, 19, 45 conv, 16
TEXtos en grficos, 45
date, 20
www.fullengineeringbook.net
Ajuste de datos, 56
Ajuste lineal, 72
datenum, 20
datestr, 20
angle, 12
ans, 12 datetick, 44
area, 48 datevec, 20
ascii, 22, 23 deconv, 16
atan2, 13 demo, 1
axes, 44 Derivadas, 27, 67
axis, 43, 44 de polinomios, 17
det, 15, 26
bar, 41 diary, 23
bar3, 46 diff, 27, 32
Bazin, ecuacin, 63 double, 28
break, 40 dsolve, 29, 32
95
96 INTRODUCCIN RPIDA A MATLAB Y SIMULINK PARA CIENCIA E INGENIERA