34
Guión N1+N2 (Pablo Guerrero) 2010/2011 cd('c:\Documents and Settings\matap.AULA\Mis Documentos') diary Sesion02 format compact % Primera hora: Resolucion de una ENL y un SENL type f2_1 function y=f2_1(x) y=log(x)-3*x+5; fplot('f2_1',[0 10]), grid Warning: Log of zero. > In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2 In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96 fplot('f2_1',[0 3]), grid Warning: Log of zero. > In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2 In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96 fplot('f2_1',[0.5 2.5]), grid fplot('f2_1',[0 0.001]), grid Warning: Log of zero. > In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2 In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96 fplot('f2_1',[0 0.01]), grid Warning: Log of zero. > In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2 In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96 type bipart % METODO DE BIPARTICION % Function [x,e,tol]=bipart(F,a,b,n) % F= nombre de la funcion a resolver % a= extremo inferior del intervalo inicial % b= " superior " " " % n= numero de iteraciones % x= solucion devuelta % e= condicion de error(e=0, correcto. e=1, intervalo inicial incorrecto) % tol= cota de |x'-x| (x'=solucion aproximada, x=solucion verdadera) function [x,e,tol]=bipart(F,a,b,n) FA=feval(F,a);FB=feval(F,b);x=(a+b)/2;FX=feval(F,x);e=0; if FA*FB>0,e=1,break,end if FA==0,x=a,break,end if FB==0,x=b,break,end % Iteraciones for k=1:n FX=feval(F,x);if FX==0,break,end if FA*FX<0, b=x;FB=feval(F,b); else a=x;FA=feval(F,a); end x=(a+b)/2; end tol=(b-a)/2; edit bipart fschange('C:\Documents and Settings\matap.AULA\Mis documentos\bipart.m'); clear bipart type bipart % METODO DE BIPARTICION % Function [x,e,tol]=bipart(F,a,b,n) % F= nombre de la funcion a resolver % a= extremo inferior del intervalo inicial % b= " superior " " " % n= numero de iteraciones Página 1 de 20

GuionN1to4

Embed Size (px)

Citation preview

Page 1: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

cd('c:\Documents and Settings\matap.AULA\Mis Documentos')

diary Sesion02

format compact

% Primera hora: Resolucion de una ENL y un SENL

type f2_1

function y=f2_1(x)

y=log(x)-3*x+5;

fplot('f2_1',[0 10]), grid

Warning: Log of zero.

> In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2

In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96

fplot('f2_1',[0 3]), grid

Warning: Log of zero.

> In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2

In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96

fplot('f2_1',[0.5 2.5]), grid

fplot('f2_1',[0 0.001]), grid

Warning: Log of zero.

> In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2

In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96

fplot('f2_1',[0 0.01]), grid

Warning: Log of zero.

> In C:\Documents and Settings\matap.AULA\Mis documentos\f2_1.m at line 2

In C:\MATLAB6p1\toolbox\matlab\specgraph\fplot.m at line 96

type bipart

% METODO DE BIPARTICION

% Function [x,e,tol]=bipart(F,a,b,n)

% F= nombre de la funcion a resolver

% a= extremo inferior del intervalo inicial

% b= " superior " " "

% n= numero de iteraciones

% x= solucion devuelta

% e= condicion de error(e=0, correcto. e=1, intervalo inicial incorrecto)

% tol= cota de |x'-x| (x'=solucion aproximada, x=solucion verdadera)

function [x,e,tol]=bipart(F,a,b,n)

FA=feval(F,a);FB=feval(F,b);x=(a+b)/2;FX=feval(F,x);e=0;

if FA*FB>0,e=1,break,end

if FA==0,x=a,break,end

if FB==0,x=b,break,end

% Iteraciones

for k=1:n

FX=feval(F,x);if FX==0,break,end

if FA*FX<0,

b=x;FB=feval(F,b);

else

a=x;FA=feval(F,a);

end

x=(a+b)/2;

end

tol=(b-a)/2;

edit bipart

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\bipart.m');

clear bipart

type bipart

% METODO DE BIPARTICION

% Function [x,e,tol]=bipart(F,a,b,n)

% F= nombre de la funcion a resolver

% a= extremo inferior del intervalo inicial

% b= " superior " " "

% n= numero de iteraciones

Página 1 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 2: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

% x= solucion devuelta

% e= condicion de error(e=0, correcto. e=1, intervalo inicial incorrecto)

% tol= cota de |x'-x| (x'=solucion aproximada, x=solucion verdadera)

function [x,e,tol,k]=bipart(F,a,b,n)

FA=feval(F,a);FB=feval(F,b);x=(a+b)/2;FX=feval(F,x);e=0;

if FA*FB>0,e=1,return,end

if FA==0,x=a,return,end

if FB==0,x=b,return,end

% Iteraciones

for k=1:n

FX=feval(F,x);if abs(FX)<=1e-12, break, end

if FA*FX<0,

b=x;FB=feval(F,b);

else

a=x;FA=feval(F,a);

end

x=(a+b)/2;

end

tol=(b-a)/2;

realmin

ans =

2.2251e-308

realmin==0

ans =

0

format long; [x,e,tol,k]=bipart('f2_1',1,2,10)

x =

1.87646484375000

e =

0

tol =

4.882812500000000e-004

k =

10

eps = 0.5e-7 % Comprobar d=7 decimales correctos

eps =

5.000000000000000e-008

f2_1(x-eps)

ans =

-4.803490404547972e-006

f2_1(x+eps)

ans =

-5.050198705447428e-006

% no tienes garantizados 7 decimales correctos

format long; [x,e,tol,k]=bipart('f2_1',1,2,30)

x =

1.87646284652874

e =

0

tol =

4.656612873077393e-010

k =

30

f2_1(x-eps)

ans =

1.238196380981549e-007

f2_1(x+eps)

ans =

-1.228886059578827e-007

% ahora si tienes garantizados 7 decimales correctos

2^40

ans =

1.099511627776000e+012

Página 2 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 3: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

2^45

ans =

3.518437208883200e+013

2^46

ans =

7.036874417766400e+013

2^47

ans =

1.407374883553280e+014

log(10^14)/log(2)

ans =

46.50699332842308

14/log10(2)

ans =

46.50699332842308

[x,e,tol,k]=bipart('f2_1',1,2,47)

x =

1.87646284671746

e =

0

tol =

4.547473508864641e-013

k =

41

eps = 0.5e-14

eps =

5.000000000000000e-015

f2_1(x-eps)

ans =

-5.950795411990839e-014

f2_1(x+eps)

ans =

-8.437694987151190e-014

edit bipart

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\bipart.m');

clear bipart

type bipart

% METODO DE BIPARTICION

% Function [x,e,tol]=bipart(F,a,b,n)

% F= nombre de la funcion a resolver

% a= extremo inferior del intervalo inicial

% b= " superior " " "

% n= numero de iteraciones

% x= solucion devuelta

% e= condicion de error(e=0, correcto. e=1, intervalo inicial incorrecto)

% tol= cota de |x'-x| (x'=solucion aproximada, x=solucion verdadera)

function [x,e,tol,k]=bipart(F,a,b,n)

FA=feval(F,a);FB=feval(F,b);x=(a+b)/2;FX=feval(F,x);e=0;

if FA*FB>0,e=1,return,end

if FA==0,x=a,return,end

if FB==0,x=b,return,end

% Iteraciones

for k=1:n

FX=feval(F,x);if abs(FX)<=1e-16, break, end

if FA*FX<0,

b=x;FB=feval(F,b);

else

a=x;FA=feval(F,a);

end

x=(a+b)/2;

end

tol=(b-a)/2;

Página 3 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 4: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

[x,e,tol,k]=bipart('f2_1',1,2,47)

x =

1.87646284671743

e =

0

tol =

3.552713678800501e-015

k =

47

f2_1(x-eps)

ans =

1.953992523340276e-014

f2_1(x+eps)

ans =

-5.329070518200751e-015

edit ej1b_intento1

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\ej1b_intento1.m');

clear ej1b_intento1

type ej1b_intento1

format long

% Primer intento

clear

x1=1;

for k=1:10

x1=(log(x1)+5)/3;

end

x1

pause

disp('A continuación comprobamos los dígitos correctos')

eps=0.5e-6

feval('f2_1',x1+eps)*feval('f2_1',x1-eps)

ej1b_intento1

x1 =

1.87646280702095

A continuación comprobamos los dígitos correctos

eps =

5.000000000000000e-007

ans =

-1.512032769899686e-012

% Se tienen 7 digitos significativos redondeados correctos

edit ej1b_intento2

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\ej1b_intento2.m');

clear ej1b_intento2

type ej1b_intento2

format long

% Segundo intento

clear

x1=1;

for k=1:10

x1=exp(3*x1-5);

end

x1

pause

disp('A continuación comprobamos los dígitos correctos')

eps=0.5e-9

feval('f2_1',x1+eps)*feval('f2_1',x1-eps)

disp('¿Tiene 7 dígitos correctos?: en caso contrario arreglar.'),

ej1b_intento2

x1 =

0.00687843098855

Página 4 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 5: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

A continuación comprobamos los dígitos correctos

eps =

5.000000000000000e-010

ans =

-5.068157941261730e-015

¿Tiene 7 dígitos correctos?: en caso contrario arreglar.

syms t real

f = 2*(1+t)+4*pi*sin(pi*t)

f =

2+2*t+4*pi*sin(pi*t)

diff(f)

ans =

2+4*pi^2*cos(pi*t)

type f3

function y=f3(x)

y=2*(1+x)+4*pi*sin(pi*x);

type df3

function dy=df3(x)

dy=2+4*pi^2*cos(pi*x);

type newton

% Metodo de Newton en una variable

function [x,e,k]=newton(F,DF,x0,n,TOL)

% F =funcion a resolver (F(x)=0)

% DF =derivada de F(x)

% x0 =punto inicial

% n =numero de iteraciones

% TOL=tolerancia (e=0, solo si |F(x)|<TOL, tras las n iteraciones)

% x =valor tras las n soluciones (solucion obtenida)

% e =condicion de error (e=0 si |F(x)|<TOL, e=1 en caso contrario,

% e=2 si DF(x)=0 en algún paso, e=3 si se produce overflow.

x=x0;e=1

for k=1:n

Fx=feval(F,x);DFx=feval(DF,x);

if DFx==0,e=2;break,end

xant=x

x=x-Fx/DFx;

if xant-x<TOL;end

if isnan(x)|isinf(x),e=3,break,end

end

if abs(feval(F,x))<TOL,e=0,end

edit newton

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\newton.m');

clear newton

type newton

% Metodo de Newton en una variable

function [x,e,k]=newton(F,DF,x0,n,TOL)

% F =funcion a resolver (F(x)=0)

% DF =derivada de F(x)

% x0 =punto inicial

% n =numero de iteraciones

% TOL=tolerancia (e=0, solo si |F(x)|<TOL, tras las n iteraciones)

% x =valor tras las n soluciones (solucion obtenida)

% e =condicion de error (e=0 si |F(x)|<TOL, e=1 en caso contrario,

% e=2 si DF(x)=0 en algún paso, e=3 si se produce overflow.

x=x0;e=1;

for k=1:n

Fx=feval(F,x);DFx=feval(DF,x);

if DFx==0,e=2;break,end

Página 5 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 6: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

xant=x;

x=x-Fx/DFx;

if abs(xant-x)<TOL, break; end

if isnan(x)|isinf(x),e=3,break,end

end

if abs(feval(F,x))<TOL,e=0,end

[x,e,k]=newton('f3','df3',1.25,100,0.5e-5)

e =

0

x =

1.10895621086418

e =

0

k =

4

fplot('f3',[-2 2]), grid

fplot('f3',[-10 10]), grid

% Un ejemplo de sistema de ENL

syms x y z real

f1 = 2*x^3-4*x-y-18

f1 =

2*x^3-4*x-y-18

f2 = -x+2*y^3-4*y-z-54

f2 =

-x+2*y^3-4*y-z-54

f3 = -y+2*z^3-4*z-133.2

f3 =

-y+2*z^3-4*z-666/5

F = [f1;f2;f3]

F =

[ 2*x^3-4*x-y-18]

[ -x+2*y^3-4*y-z-54]

[ -y+2*z^3-4*z-666/5]

JF = jacobian(F)

JF =

[ 6*x^2-4, -1, 0]

[ -1, 6*y^2-4, -1]

[ 0, -1, 6*z^2-4]

type f5

function z=f5(u)

x=u(1);

y=u(2);

z=u(3);

z=[2*x.^3-4*x-y-18;

-x+2*y.^3-4*y-z-54;

-y+2*z.^3-4*z-133.2];

type jf5

function z=jf5(u)

x=u(1);

y=u(2);

z=u(3);

z=[6*x.^2-4 -1 0;

-1 6*y.^2-4 -1;

0 -1 6*z.^2-4];

type newton2

function [z,e]=newton2(F,J,x0,n)

% F = sistema a resolver

% J = jacobiano

% x0 = punto inicial

Página 6 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 7: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

% n = numero de iteraciones

% z = solucion obtenida

% e = condicion de error

e=1;

x=x0;

for k=1:n,

S=feval(F,x);

A=feval(J,x);

incx=A\(-S);

x=x+incx;

% x=x-S*inv(A) %Sustituye a las 2 anteriores

end

if isnan(x)|isinf(x),e=1;else,e=0;end

z=x;

[x,e]=newton2('f5','jf5',[3;4;5],100)

x =

2.50249039110781

3.33352116372087

4.25002175953674

e =

0

format short

% El residual de un SENL es F(x^*)

f5(x)

ans =

1.0e-013 *

0

0

-0.5684

norm(ans)

ans =

5.6843e-014

edit newton2

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\newton2.M');

type newton2

function [z,e,k]=newton2(F,J,x0,n)

% F = sistema a resolver

% J = jacobiano

% x0 = punto inicial

% n = numero de iteraciones

% z = solucion obtenida

% e = condicion de error

e=1;

x=x0;

for k=1:n

S=feval(F,x);

A=feval(J,x);

incx=A\(-S);

if norm(incx)<1e-6, break; end;

x=x+incx;

% x=x-S*inv(A) %Sustituye a las 2 anteriores

end

if isnan(x)|isinf(x),e=1;else,e=0;end

z=x;

[x,e,k]=newton2('f5','jf5',[3;4;5],100)

x =

2.5025

3.3335

4.2500

e =

0

Página 7 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 8: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

k =

5

f5(x)

ans =

1.0e-009 *

0.3650

0.4818

0.1148

norm(ans)

ans =

6.1523e-010

% Segunda hora: Optimizacion

% Funciones de IR en IR

% E1

% f = x^2 - 5*sin(x) en [-pi,pi]

% fprima = 2*x - 5*cos(x)

% fsegunda = 2 + 5*sin(x)

type p3_1

fplot('x^2-5*sin(x)',[-pi, pi]), grid

disp('Se observa que el mínimo es interior prox a 1 y el/los máximos son extremos.')

% Para resolver g(x)=0

% Usamos Newton: x=x-g(x)/g'(x)

% Para calcular puntos críticos: f'(x)=0

% Por tanto Newton: x=x-f'(x)/f''(x)

% f'(x)=2x-5cos(x)%

% f''(x)=2+5*sin(x)%

dF=inline('2*x-5*cos(x)');

d2F=inline('2+5*sin(x)');

% AYUDA: Puedes usar la orden diff de matlab para calcular derivadas

x=1;

for k=1:20;

x=x-(dF(x))/(d2F(x));

end

[x,x^2-5*sin(x)]

[-pi,pi^2-5*sin(-pi)]

[pi,pi^2-5*sin(pi)]

fplot('x^2-5*sin(x)',[-pi, pi]), grid

df=inline('2*x-5*cos(x)')

df =

Inline function:

df(x) = 2*x-5*cos(x)

d2f=inline('2+5*sin(x)')

d2f =

Inline function:

d2f(x) = 2+5*sin(x)

format long; x=1

x =

1

for k=1:10, x = x - df(x)/d2f(x), end;

x =

1.11301295606989

x =

1.11051157231207

x =

1.11051050358131

x =

1.11051050358111

x =

1.11051050358111

x =

1.11051050358111

Página 8 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 9: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

x =

1.11051050358111

x =

1.11051050358111

x =

1.11051050358111

x =

1.11051050358111

[x, x^2 - 5*sin(x)] % [minimo, valor minimo]

ans =

1.11051050358111 -3.24639427269154

df(x)

ans =

-4.440892098500626e-016

d2f(x)

ans =

6.47962785125551

% ahora ya tengo garantizado que en x hay un minimo local estricto

% ... y por la forma de la funcion, es tambien minimo global

% Para los maximos globales RESTRINGIDOS se hace ...

x = -pi; [x, x^2 - 5*sin(x)] % [maximo, valor maximo]

ans =

-3.14159265358979 9.86960440108936

x = pi; [x, x^2 - 5*sin(x)] % [maximo, valor maximo]

ans =

3.14159265358979 9.86960440108936

% Luego maximos globales restringidos en -pi y en pi

% OJO: en los RESTRINGIDOS no tiene por que anularse la derivada!!!

df(-pi), df(pi)

ans =

-1.28318530717959

ans =

11.28318530717959

fplot(df,[-3.3 3.3]), grid on % la grafica de la derivada

% En Matlab para resolver una ENL se usa el metodo de Brent (fzero)

fzero(df,3) % o bien fzero('2*x-5*cos(x)',3)

ans =

1.11051050358111

% E2

syms x real

f = 2*exp(-x)*sin(x)

f =

2*exp(-x)*sin(x)

diff(f)

ans =

-2*exp(-x)*sin(x)+2*exp(-x)*cos(x)

solve(ans)

ans =

1/4*pi

ezplot(f,[0 8]); grid

f = '2*exp(-x).*sin(x)'; fplot(f,[0 8]); grid

% Para minimizacion irrestringida en una variable Matlab tiene fmin

xmin = fmin(f,2,5)

Warning: FMIN is obsolete and has been replaced by FMINBND.

FMIN now calls FMINBND which uses the following syntax:

[X,FVAL,EXITFLAG,OUTPUT] = FMINBND(FUN,x1,x2,OPTIONS,P1,P2,...)

Use OPTIMSET to define optimization options, or type

'edit fmin' to view the code used here. FMIN will be

removed in the future; please use FMINBND with the new syntax.

> In C:\MATLAB6p1\toolbox\matlab\funfun\fmin.m at line 62

xmin =

3.92698936464428

emin = xmin - 5*pi/4

Página 9 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 10: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

emin =

-1.452342966334896e-006

x = xmin; ymin = eval(f)

ymin =

-0.02786407019533

% ymin es el valor minimo, xmin es el minimo

g = '-2*exp(-x).*sin(x)'; fplot(g,[0 8]); grid

xmax = fmin(g,0,3)

Warning: FMIN is obsolete and has been replaced by FMINBND.

FMIN now calls FMINBND which uses the following syntax:

[X,FVAL,EXITFLAG,OUTPUT] = FMINBND(FUN,x1,x2,OPTIONS,P1,P2,...)

Use OPTIMSET to define optimization options, or type

'edit fmin' to view the code used here. FMIN will be

removed in the future; please use FMINBND with the new syntax.

> In C:\MATLAB6p1\toolbox\matlab\funfun\fmin.m at line 62

xmax =

0.78541194448879

emax = xmax - pi/4

emax =

1.378109134475558e-005

x = xmax; ymax = eval(f) % o bien ymax = -eval(g)

ymax =

0.64479388376721

% ymax es el valor maximo, xmax es el maximo ...

% ... siempre y cuando se verifiquen las condiciones ...

% ... suficientes de optimalidad de primer y segundo orden

% Funciones de IR^n en IR (i.e., optimizacion de campos escalares)

% E4

syms x1 x2 real

f = (x1-2)^4 + (x1-2*x2)^2

f =

(x1-2)^4+(x1-2*x2)^2

nablaf = jacobian(f)'

nablaf =

[ 4*(x1-2)^3+2*x1-4*x2]

[ -4*x1+8*x2]

nabla2f = jacobian(nablaf)'

nabla2f =

[ 12*(x1-2)^2+2, -4]

[ -4, 8]

subs(nablaf,{x1,x2},{2,1})

ans =

0

0

subs(nabla2f,{x1,x2},{2,1})

ans =

[ 2, -4]

[ -4, 8]

double(ans)

ans =

2 -4

-4 8

eig(ans)

ans =

0

10

type f5p3

function z=f5p3(u)

x1=u(1); x2=u(2);

z=(x1-2).^4+(x1-2*x2).^2;

type df5p3

Página 10 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 11: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

function dY=df5p3(u)

x1=u(1); x2=u(2);

dY=[4*(x1-2).^3+2*(x1-2*x2);

-4*(x1-2*x2) ];

type d2f5p3

function d2Y=d2f5p3(u)

x1=u(1); x2=u(2);

d2Y=[ 12*(x1-2).^2+2 -4;

-4 8];

type p3_5

% Localizamos el máximo de la función. Está en [0,3]^T ?

[x1,x2]=meshgrid(0:0.1:3,0:0.1:3);

contour(x1,x2,(x1-2).^4+(x1-2*x2).^2,0:40);

meshc(x1,x2,(x1-2).^4+(x1-2*x2).^2);

pause;

% Utilizando fmins de MATLAB

xmin=fmins('f5p3',[3 3]'),

ymin=f5p3(xmin)

% Utilizando newton2.m

xf=newton2('df5p3','d2f5p3',[3 3]',100)

yf=f5p3(xf)

[xf,e,k]=newton2('df5p3','d2f5p3',[3;3],100)

xf =

2.00000231781944

1.00000115890972

e =

0

k =

33

yf = f5p3(xf) % yf valor minimo?, xf minimo?

yf =

2.886146738239224e-023

df5p3(xf), norm(ans)

ans =

1.0e-016 *

0.49807964890282

0

ans =

4.980796489028181e-017

d2f5p3(xf), eig(ans)

ans =

2.00000000006447 -4.00000000000000

-4.00000000000000 8.00000000000000

ans =

0.00000000005157

10.00000000001289

% Pintar campos escalares

type p3_5

% Localizamos el máximo de la función. Está en [0,3]^T ?

[x1,x2]=meshgrid(0:0.1:3,0:0.1:3);

contour(x1,x2,(x1-2).^4+(x1-2*x2).^2,0:40);

meshc(x1,x2,(x1-2).^4+(x1-2*x2).^2);

pause;

% Utilizando fmins de MATLAB

Página 11 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 12: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

xmin=fmins('f5p3',[3 3]'),

ymin=f5p3(xmin)

% Utilizando newton2.m

xf=newton2('df5p3','d2f5p3',[3 3]',100)

yf=f5p3(xf)

[x1,x2]=meshgrid(0:0.1:3,0:0.1:3);

meshc(x1,x2,(x1-2).^4+(x1-2*x2).^2); % CON OPERADORES ELEMENTO A ELEMENTO

Warning: Unrecognized OpenGL version, defaulting to 1.0.

Warning: Unrecognized OpenGL version, defaulting to 1.0.

Warning: Unrecognized OpenGL version, defaulting to 1.0.

surf(x1,x2,(x1-2).^4+(x1-2*x2).^2); % CON OPERADORES ELEMENTO A ELEMENTO

Warning: Unrecognized OpenGL version, defaulting to 1.0.

Warning: Unrecognized OpenGL version, defaulting to 1.0.

Warning: Unrecognized OpenGL version, defaulting to 1.0.

surfc(x1,x2,(x1-2).^4+(x1-2*x2).^2); % CON OPERADORES ELEMENTO A ELEMENTO

Warning: Unrecognized OpenGL version, defaulting to 1.0.

Warning: Unrecognized OpenGL version, defaulting to 1.0.

Warning: Unrecognized OpenGL version, defaulting to 1.0.

[c,h]=contour(x1,x2,(x1-2).^4+(x1-2*x2).^2,15); % 15 curvas de nivel

[c,h]=contour(x1,x2,(x1-2).^4+(x1-2*x2).^2,[0 0]); % La curva de nivel 0

[c,h]=contour(x1,x2,(x1-2).^4+(x1-2*x2).^2,0:40); % Las curvas de 0 a 40

clabel(c,h,0:5:40)

% Para buscar minimos locales en varias variables existe fmins (metodo Nelder-Mead)

xmin=fmins('f5p3',[3;3]), ymin=f5p3(xmin)

Warning: FMINS is obsolete and has been replaced by FMINSEARCH.

FMINS now calls FMINSEARCH which uses the following syntax:

[X,FVAL,EXITFLAG,OUTPUT] = FMINSEARCH(FUN,X0,OPTIONS,P1,P2,...)

Use OPTIMSET to define optimization options, or type

'edit fmins' to view the code used here. FMINS will be

removed in the future; please use FMINSEARCH with the new syntax.

> In C:\MATLAB6p1\toolbox\matlab\funfun\fmins.m at line 66

xmin =

2.00011408977858

1.00005705701588

ymin =

7.576448641400849e-016

% E5 (con minimo, no con maximo)

syms x y real

f = (3-x+y)^4 + (4-y)^2 + x - y

f =

(3-x+y)^4+(4-y)^2+x-y

nablaf = jacobian(f)'

nablaf =

[ -4*(3-x+y)^3+1]

[ 4*(3-x+y)^3-9+2*y]

nabla2f = jacobian(nablaf)'

nabla2f =

[ 12*(3-x+y)^2, -12*(3-x+y)^2]

[ -12*(3-x+y)^2, 12*(3-x+y)^2+2]

type f4p3

function z=f4p3(u)

x=u(1);y=u(2); A=4*(3-x+y)^3;

z=[-A+1;

A-2*(4-y)-1];

type jf4p3

function u=jf4p3(X)

x=X(1);y=X(2); A=12*(3-x+y)^2;

u=[A -A;

Página 12 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 13: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

-A A+2];

[x,y]=meshgrid(-10:0.1:10,-10:0.1:10);

contour(x,y,(3-x+y)^4+(4-y)^2+x-y,150); % Asi esta MAL !!!!!!

contour(x,y,(3-x+y).^4+(4-y).^2+x-y,150); % Asi esta BIEN !!!!!!

[x,y]=meshgrid(5:0.1:7,3:0.1:5);

contour(x,y,(3-x+y).^4+(4-y).^2+x-y,150); % Asi esta BIEN !!!!!!

[xf,e,k]=newton2('f4p3','jf4p3',[-7;-4],25)

xf =

6.37003947237539

4.00000000000000

e =

0

k =

10

hold on; plot(xf(1),xf(2),'o'); hold off;

f4p3(xf), norm(ans)

ans =

1.0e-007 *

-0.12749253652800

0.12749253652800

ans =

1.803016742592385e-008

jf4p3(xf), eig(ans)

ans =

4.76220319638096 -4.76220319638096

-4.76220319638096 6.76220319638096

ans =

0.89613915204071

10.62826724072120

H = jf4p3(xf); det(H(1:1,1:1)), det(H(1:2,1:2))

ans =

4.76220319638096

ans =

9.52440639276191

% luego efectivamente habia un minimo local estricto en xf

[xf,e,k]=newton2('f4p3','jf4p3',[-7;4],25)

xf =

6.37003946643627

4.00000000000000

e =

0

k =

12

H = jf4p3(xf), det(H(1:1,1:1)), det(H(1:2,1:2))

H =

4.76220328617476 -4.76220328617476

-4.76220328617476 6.76220328617476

ans =

4.76220328617476

ans =

9.52440657234952

% Tercera hora: Algebra Lineal Numerica

help lu

LU LU factorization.

[L,U] = LU(X) stores an upper triangular matrix in U and a

"psychologically lower triangular matrix" (i.e. a product

of lower triangular and permutation matrices) in L, so

that X = L*U. X can be rectangular.

[L,U,P] = LU(X) returns lower triangular matrix L, upper

triangular matrix U, and permutation matrix P so that

P*X = L*U.

Página 13 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 14: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

LU(X), with one output argument, returns the output from

LAPACK'S DGETRF or ZGETRF routine.

LU(X,THRESH) controls pivoting in sparse matrices, where

THRESH is a pivot threshold in [0,1]. Pivoting occurs

when the diagonal entry in a column has magnitude less than

THRESH times the magnitude of any sub-diagonal entry in that

column. THRESH = 0 forces diagonal pivoting. THRESH = 1 is

the default.

See also LUINC, QR, RREF.

type gausspar

function [x,e]=gausspar(A,B)

[m,n]=size(A);

[m1,n1]=size(B);

% Comprobacion errores

if m~=n, e=1;return,end

if m1~=m, e=1;return,end

C=[A B];

% Bucle pincipal

for k=1:m-1,

% Intercambio de filas

[i,ii]=max(abs(C(k:m,k)));ii=ii+k-1;

if ii~=k, d=C(k,:);C(k,:)=C(ii,:);C(ii,:)=d;end

% Triangularizacion

for l=k+1:m,

coef=C(l,k)/C(k,k);

C(l,:)=C(l,:)-coef*C(k,:);

end

end

x=sustreg(C(:,1:m),C(:,m+1:m+n1));

type sustreg

function [x,e]=sustreg(A,b)

[m,n]=size(A);[m1,n1]=size(b);

if m~=n, e=1;return,end

if n~=m1,e=1;return,end

for k=n:-1:1,

x(k,:)=b(k,:)/A(k,k);

for t=1:k-1,

b(t,:)=b(t,:)-A(t,k)*x(k,:);

end

end

type doolittle

function x=doolittle(A,b)

[L,U,P]=lu(A);

bb=P*b;

y=sustprog(L,bb);

x=sustreg(U,y);

type solqr

function x=solqr(A,b)

[m,n]=size(A);

[Q,R]=qr(A);

Página 14 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 15: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

bb=Q'*b;

x=sustreg(R(1:n,1:n),bb(1:n,:));

% en vez de x=sustreg(R(1:n,1:n),bb(1:n,:));

% se puede hacer x=R(1:n,1:n)\bb(1:n);

% E6

dir

. doolittle.m p3_4.m

.. f4p3.m p3_5.m

Archivos_MATLAB_Pract2.zip f5p3.m p3_6.m

Pizarra.pdf gauss.m practica_3.zip

Sesion03 gaussjor.m sistema.m

TkitP02b.pdf gausspar.m sistema2.m

TkitP03.pdf gausstot.m sistemasobre.m

cholesky.m jf4p3.m solqr.m

d2f5p3.m metpoten.m sustprog.m

desktop.ini newton2.M sustreg.m

df5p3.m p3_1.m

clear all

whos

sistema

whos

Name Size Bytes Class

A 10x10 800 double array

b 10x1 80 double array

Grand total is 110 elements using 880 bytes

x = A\b; r = b - A*x; % residual definido segun [Faires & Burden, 2003]

norm(r)

ans =

1.227599960444820e-014

% Residual pequeño indica cercania a la solucion?

% Si, siempre y cuando el sistema no sea muy mal condicionado

cond(A)

ans =

91.33843294546598

% E8 (sistemas sobredeterminados)

b = [1 3 5 -2]'

b =

1

3

5

-2

A1 = [1 1 1; 0 0 1; 1 -1 0; 1 0 1]

A1 =

1 1 1

0 0 1

1 -1 0

1 0 1

A2 = [1 2;1 2;1 2;1 2]

A2 =

1 2

1 2

1 2

1 2

A3 = [1 4 7 2; 2 5 8 5; 3 6 0 8]

A3 =

1 4 7 2

2 5 8 5

3 6 0 8

Página 15 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 16: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

rank(A1), rank(A2), rank(A3)

ans =

3

ans =

1

ans =

3

A1'*A1, A2'*A2, A3*A3', A3'*A3

ans =

3 0 2

0 2 1

2 1 3

ans =

4 8

8 16

ans =

70 88 43

88 118 76

43 76 109

ans =

14 32 23 36

32 77 68 81

23 68 113 54

36 81 54 93

eig(A1'*A1), eig(A2'*A2), eig(A3*A3'), eig(A3'*A3)

ans =

0.60861761936910

2.22713444217069

5.16424793846021

ans =

0

20

ans =

1.0e+002 *

0.00675884844813

0.54517643519882

2.41806471635305

ans =

1.0e+002 *

-0.00000000000000

0.00675884844813

0.54517643519882

2.41806471635305

A1\b, norm(ans), pinv(A1)*b, norm(ans)

ans =

0.57142857142857

-2.57142857142857

1.14285714285714

ans =

2.87139303460597

ans =

0.57142857142857

-2.57142857142857

1.14285714285714

ans =

2.87139303460597

A2\b, norm(ans), pinv(A2)*b, norm(ans)

Warning: Rank deficient, rank = 1 tol = 3.5527e-015.

ans =

0

0.87500000000000

ans =

0.87500000000000

ans =

Página 16 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 17: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

0.35000000000000

0.70000000000000

ans =

0.78262379212493

solqr(A1,b), norm(ans), solqr(A2,b), norm(ans)

ans =

0.57142857142857

-2.57142857142857

1.14285714285714

ans =

2.87139303460597

ans =

1.0e+015 *

-2.25179981368525

1.12589990684262

ans =

2.517588727560786e+015

% E12

clear all

whos

sistema2

A =

Columns 1 through 4

6.27000000000000 0.32000000000000 1.35000000000000 1.32000000000000

0.32000000000000 5.11000000000000 0.01000000000000 -1.33000000000000

1.35000000000000 0.01000000000000 7.77000000000000 1.11000000000000

1.32000000000000 -1.33000000000000 1.11000000000000 4.00000000000000

2.10000000000000 1.10000000000000 2.21000000000000 0.05000000000000

Column 5

2.10000000000000

1.10000000000000

2.21000000000000

0.05000000000000

6.50000000000000

b =

2.76000000000000

2.23000000000000

-1.23000000000000

3.78000000000000

7.10000000000000

whos

Name Size Bytes Class

A 5x5 200 double array

b 5x1 40 double array

Grand total is 30 elements using 240 bytes

[V,D]=eig(A)

V =

Columns 1 through 4

0.35655213400190 -0.35938344805588 0.71352189189924 0.00281499338042

-0.40804491347753 -0.55077205800361 -0.13822563167003 0.70902901198165

0.14464790921075 -0.25365422213147 -0.63381920720811 -0.31980926522185

-0.81472269770598 -0.05426625872723 0.26036320986760 -0.48326356559803

-0.14722035364534 0.70725411709269 0.04758567065268 0.40180629166842

Column 5

0.48434770423215

0.09121964495284

0.64088358100998

0.17874401841561

0.56071836892703

D =

Columns 1 through 4

Página 17 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 18: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

2.56816716088315 0 0 0

0 3.77984100470621 0 0

0 0 5.63052587643107 0

0 0 0 6.63663734490201

0 0 0 0

Column 5

0

0

0

0

11.03482861307755

D(5,5)

ans =

11.03482861307755

V(:,5), norm(ans), norm(A*V-V*D)

ans =

0.48434770423215

0.09121964495284

0.64088358100998

0.17874401841561

0.56071836892703

ans =

1

ans =

4.909227278057077e-015

% E13: El sistema sobredeterminado es Ma=y, con y=sen(x), x vector columna

x = (0:0.1:1)'; y = sin(x)

y =

0

0.0998

0.1987

0.2955

0.3894

0.4794

0.5646

0.6442

0.7174

0.7833

0.8415

M = fliplr(vander(x)); M(:,4:end) = [] % EJERCICIO: ir incrementando el 4

M =

1.0000 0 0

1.0000 0.1000 0.0100

1.0000 0.2000 0.0400

1.0000 0.3000 0.0900

1.0000 0.4000 0.1600

1.0000 0.5000 0.2500

1.0000 0.6000 0.3600

1.0000 0.7000 0.4900

1.0000 0.8000 0.6400

1.0000 0.9000 0.8100

1.0000 1.0000 1.0000

format long

aDI = M\y, norm(aDI)

aDI =

-0.00531589475039

1.08657753288357

-0.23475859938224

ans =

1.11166118655292

aPS = pinv(M)*y, norm(aPS)

aPS =

-0.00531589475039

1.08657753288357

Página 18 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 19: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

-0.23475859938224

ans =

1.11166118655292

aQR = solqr(M,y), norm(aQR)

aQR =

-0.00531589475039

1.08657753288357

-0.23475859938224

ans =

1.11166118655292

[Q,R] = qr(M), c = Q'*y, aQR = R(1:3,1:3)\c(1:3) % Lo mismo que solqr y sobredqr

Q =

Columns 1 through 4

-0.30151134457776 -0.47673129462280 0.51209155649919 -0.07597291962053

-0.30151134457776 -0.38138503569824 0.20483662259968 -0.02391753073257

-0.30151134457776 -0.28603877677368 -0.03413943709995 -0.34738516752142

-0.30151134457776 -0.19069251784912 -0.20483662259968 0.88911449839737

-0.30151134457776 -0.09534625892456 -0.30725493389951 -0.13750870067530

-0.30151134457776 -0.00000000000000 -0.34139437099946 -0.14484959252064

-0.30151134457776 0.09534625892456 -0.30725493389951 -0.13290817713865

-0.30151134457776 0.19069251784912 -0.20483662259968 -0.10168445452934

-0.30151134457776 0.28603877677368 -0.03413943709995 -0.05117842469271

-0.30151134457776 0.38138503569824 0.20483662259968 0.01860991237125

-0.30151134457776 0.47673129462280 0.51209155649919 0.10768055666254

Columns 5 through 8

0.00619444923634 0.03924553795239 0.02318034652763 -0.04200112503796

0.11203216294592 0.22125543881471 0.30375229687379 0.35952273712317

-0.40814801840302 -0.41413092921796 -0.36533389996626 -0.26175693064790

-0.11156515281398 -0.10531002234856 -0.09212011020638 -0.07199541638743

0.84513585581569 -0.15850830489152 -0.14844118279693 -0.12466277790054

-0.17325573578496 0.81482309189485 -0.18061310948121 -0.15956433991313

-0.16673992761594 -0.18531583198946 0.81136410974079 -0.17670010242520

-0.13531671967724 -0.15892507654444 -0.17250952513094 0.82392993456326

-0.07898611196887 -0.10600464177010 -0.13223401409640 -0.15767422894776

0.00225189550917 -0.02655452766644 -0.06780935715559 -0.12151259295826

0.10839730275689 0.07942526576654 0.02076444569150 -0.06758515746824

Columns 9 through 11

-0.15629887674437 -0.31971290859160 -0.53224322057964

0.38856675956284 0.39088436419280 0.36647555101307

-0.10340002126289 0.10973682818876 0.37765361770707

-0.04493594089171 -0.01094168371922 0.02998735513003

-0.08717309020235 -0.03597211970236 0.02894013359943

-0.12203059940092 -0.06801188794458 0.00249179445590

-0.14950846848742 -0.10706098844587 -0.04935766230055

-0.16960669746184 -0.15311942120624 -0.12660823666994

0.81767471367581 -0.20618718622568 -0.22925992865224

-0.18766423507447 0.73373571649579 -0.35731273824748

-0.18562354371268 -0.33335071304181 0.48923333454436

R =

-3.31662479035540 -1.65831239517770 -1.16081867662439

0 1.04880884817015 1.04880884817015

0 0 0.29291637031754

0 0 0

0 0 0

0 0 0

0 0 0

0 0 0

0 0 0

0 0 0

0 0 0

c =

-1.51174199612928

0.89339523449505

-0.06876463683188

Página 19 de 20

Usuario
Highlight
Usuario
Highlight
Page 20: GuionN1to4

Guión N1+N2 (Pablo Guerrero) 2010/2011

-0.00372222290838

-0.00182939994747

0.00058386072006

0.00261823694124

0.00342226927260

0.00220086848152

-0.00177674018507

-0.00916971534084

aQR =

-0.00531589475039

1.08657753288357

-0.23475859938224

[Q,R] = qr(M,0), c = Q'*y, aQR = R(1:3,1:3)\c(1:3), norm(aQR) % Mismo que solqr?

Q =

-0.30151134457776 -0.47673129462280 0.51209155649919

-0.30151134457776 -0.38138503569824 0.20483662259968

-0.30151134457776 -0.28603877677368 -0.03413943709995

-0.30151134457776 -0.19069251784912 -0.20483662259968

-0.30151134457776 -0.09534625892456 -0.30725493389951

-0.30151134457776 -0.00000000000000 -0.34139437099946

-0.30151134457776 0.09534625892456 -0.30725493389951

-0.30151134457776 0.19069251784912 -0.20483662259968

-0.30151134457776 0.28603877677368 -0.03413943709995

-0.30151134457776 0.38138503569824 0.20483662259968

-0.30151134457776 0.47673129462280 0.51209155649919

R =

-3.31662479035540 -1.65831239517770 -1.16081867662439

0 1.04880884817015 1.04880884817015

0 0 0.29291637031754

c =

-1.51174199612928

0.89339523449505

-0.06876463683188

aQR =

-0.00531589475039

1.08657753288357

-0.23475859938224

ans =

1.11166118655292

aEN = (M'*M)\(M'*y), norm(aEN)

aEN =

-0.00531589475039

1.08657753288358

-0.23475859938225

ans =

1.11166118655294

cond(M) % || M ||_2 por || pinv(M) ||_2

ans =

19.48728345301832

diary off

quit

Página 20 de 20

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 21: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

cd('c:\Documents and Settings\matap.AULA\Mis Documentos')

diary Sesion04

format compact

% Primera hora: interpolacion y aproximacion

% Puntos {x_0,x_1,...,x_n} => grado polinomio interpolante es n

% E1 (n = 5)

format long; x = [0 3 -5 6 8 1]; y = [-5 -2 -10 0 -1 -3]; p = polyfit(x,y,5)

p =

Columns 1 through 4

-0.00242535242535 0.02778332778333 -0.01189366189366 -0.71659451659452

Columns 5 through 6

2.70313020313021 -5.00000000000000

xs = linspace(min(x),max(x)); ys = polyval(p,xs);

plot(xs,ys); hold on; plot(x,y,'o'); grid, hold off;

polyval(p,0.5), polyval(p,8)

ans =

-3.82740956959707

ans =

-1.00000000000001

% E2

type p4_2

x=0:0.1:5;

n=6;

g=1./sqrt((2-x).^2+x.^2);

ag=polyfit(x,g,n);

y=polyval(ag,x);

plot(x,y,'y-',x,g,'g:');

x=(0:0.1:5)'; n=6; g=1./sqrt((2-x).^2+x.^2);

M=ones(size(x)); for k = 1:6, M(:,k+1) = x.*M(:,k); end; size(M)

ans =

51 7

% Todas las columnas de M son linealmente independientes, pero...

rank(M), cond(M)

ans =

7

ans =

3.857219720341935e+005

[Q,R]=qr(fliplr(M),0); ag=R\(Q'*g)

ag =

0.00209482202256

-0.03155583865000

0.16998039754128

-0.35770836109786

0.09690388133430

0.32549193600065

0.48981286150449

polyfit(x,g,n)

ans =

Columns 1 through 4

0.00209482202256 -0.03155583865000 0.16998039754128 -0.35770836109786

Columns 5 through 7

0.09690388133430 0.32549193600065 0.48981286150449

[ag polyfit(x,g,n)']

ans =

0.00209482202256 0.00209482202256

-0.03155583865000 -0.03155583865000

0.16998039754128 0.16998039754128

-0.35770836109786 -0.35770836109786

0.09690388133430 0.09690388133430

0.32549193600065 0.32549193600065

0.48981286150449 0.48981286150449

% Son los mismos, pero no es casualidad porque ...

Página 1 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 22: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

type polyfit

function [p,S,mu] = polyfit(x,y,n)

%POLYFIT Fit polynomial to data.

% POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) of

% degree N that fits the data, P(X(I))~=Y(I), in a least-squares sense.

%

% [P,S] = POLYFIT(X,Y,N) returns the polynomial coefficients P and a

% structure S for use with POLYVAL to obtain error estimates on

% predictions. If the errors in the data, Y, are independent normal

% with constant variance, POLYVAL will produce error bounds which

% contain at least 50% of the predictions.

%

% The structure S contains the Cholesky factor of the Vandermonde

% matrix (R), the degrees of freedom (df), and the norm of the

% residuals (normr) as fields.

%

% [P,S,MU] = POLYFIT(X,Y,N) finds the coefficients of a polynomial

% in XHAT = (X-MU(1))/MU(2) where MU(1) = mean(X) and MU(2) = std(X).

% This centering and scaling transformation improves the numerical

% properties of both the polynomial and the fitting algorithm.

%

% Warning messages result if N is >= length(X), if X has repeated, or

% nearly repeated, points, or if X might need centering and scaling.

%

% See also POLY, POLYVAL, ROOTS.

% Copyright 1984-2001 The MathWorks, Inc.

% $Revision: 5.15 $ $Date: 2001/04/15 11:59:13 $

% The regression problem is formulated in matrix format as:

%

% y = V*p or

%

% 3 2

% y = [x x x 1] [p3

% p2

% p1

% p0]

%

% where the vector p contains the coefficients to be found. For a

% 7th order polynomial, matrix V would be:

%

% V = [x.^7 x.^6 x.^5 x.^4 x.^3 x.^2 x ones(size(x))];

if ~isequal(size(x),size(y))

error('X and Y vectors must be the same size.')

end

x = x(:);

y = y(:);

if nargout > 2

mu = [mean(x); std(x)];

x = (x - mu(1))/mu(2);

end

% Construct Vandermonde matrix.

V(:,n+1) = ones(length(x),1);

for j = n:-1:1

V(:,j) = x.*V(:,j+1);

end

% Solve least squares problem, and save the Cholesky factor.

Página 2 de 14

Usuario
Highlight
Page 23: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

[Q,R] = qr(V,0);

ws = warning('off');

p = R\(Q'*y); % Same as p = V\y;

warning(ws);

if size(R,2) > size(R,1)

warning('Polynomial is not unique; degree >= number of data points.')

elseif condest(R) > 1.0e10

if nargout > 2

warning(sprintf( ...

['Polynomial is badly conditioned. Remove repeated data points.']))

else

warning(sprintf( ...

['Polynomial is badly conditioned. Remove repeated data points\n' ...

' or try centering and scaling as described in HELP

POLYFIT.']))

end

end

r = y - V*p;

p = p.'; % Polynomial coefficients are row vectors by convention.

% S is a structure containing three elements: the Cholesky factor of the

% Vandermonde matrix, the degrees of freedom and the norm of the residuals.

S.R = R;

S.df = length(y) - (n+1);

S.normr = norm(r);

% Tambien se puede resolver Ma=g y hacer flipud(a), o bien hat{M}hat{a} = g con DI

[ag flipud(M\g) fliplr(M)\g]

ans =

0.00209482202256 0.00209482202256 0.00209482202256

-0.03155583865000 -0.03155583865000 -0.03155583865000

0.16998039754128 0.16998039754128 0.16998039754128

-0.35770836109786 -0.35770836109786 -0.35770836109786

0.09690388133430 0.09690388133430 0.09690388133430

0.32549193600065 0.32549193600065 0.32549193600065

0.48981286150449 0.48981286150449 0.48981286150449

% Error: diferencia entre g y phi, es decir, || g - fliplr(M)*ag ||_2

% Luego norm(g - phi), que equivale a norm(g - hat{M}hat{a})

error = norm(g-fliplr(M)*ag)

error =

0.05195107629169

y = polyval(ag,x); % Pero y coincide con hat{M}hat{a}, i.e., y es la

plot(x,y,'b-',x,g,'r:') % aproximacion phi (azul), g es la funcion original (rojo)

% E3 (n = 10)

type p4_3

x=0:0.1:1;

y=[-.447 1.978 3.28 6.16 7.08 7.34 7.66 9.56 9.48 9.3 11.2];

fi2=polyfit(x,y,2)

xi=linspace(0,1,100);

zi=polyval(fi2,xi);

% Marcamos con x los puntos y en verde fi2

plot(x,y,'x',xi,zi,'g');

pause;

pe10=polyfit(x,y,10),

hold on;

yi=polyval(pe10,xi);

% En verde pe10

plot(xi,yi,'b');

hold off

format short

x=0:0.1:1;

Página 3 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 24: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

y=[-.447 1.978 3.28 6.16 7.08 7.34 7.66 9.56 9.48 9.3 11.2];

fi=polyfit(x,y,2)

fi =

-9.8108 20.1293 -0.0317

% Marcamos con o los puntos de la nube y en rojo y discontinuo la phi

xi=linspace(0,1,100); zi=polyval(fi,xi); plot(x,y,'o',xi,zi,'r:')

pe10=polyfit(x,y,10)

pe10 =

1.0e+006 *

Columns 1 through 8

-0.4644 2.2965 -4.8773 5.8233 -4.2948 2.0211 -0.6032 0.1090

Columns 9 through 11

-0.0106 0.0004 -0.0000

yi = polyval(pe10,xi); hold on; plot(xi,yi,'b'); hold off;

% polinomio interpolador en azul

% Se observa el fenomeno del "polynomial wiggle"

% E9 (ya explicado al final de N1+N2)

% El sistema es Ma=y, con y=sen(x), x vector columna

x = (0:0.1:1)';

M=ones(size(x)); for k = 1:2, M(:,k+1) = x.*M(:,k); end; size(M)

ans =

11 3

M = fliplr(vander(x)); M(:,4:end) = []; y = sin(x);

format long; [flipud(M\y) polyfit(x,y,2)'], format short;

ans =

-0.23475859938224 -0.23475859938224

1.08657753288357 1.08657753288357

-0.00531589475039 -0.00531589475039

% Se obtienen los mismos resultados

% Segunda hora: integracion y derivacion numerica

% E15

type humps

function [out1,out2] = humps(x)

%HUMPS A function used by QUADDEMO, ZERODEMO and FPLOTDEMO.

% Y = HUMPS(X) is a function with strong maxima near x = .3

% and x = .9.

%

% [X,Y] = HUMPS(X) also returns X. With no input arguments,

% HUMPS uses X = 0:.05:1.

%

% Example:

% plot(humps)

%

% See QUADDEMO, ZERODEMO and FPLOTDEMO.

% Copyright 1984-2001 The MathWorks, Inc.

% $Revision: 5.7 $ $Date: 2001/04/15 12:03:04 $

if nargin==0, x = 0:.05:1; end

y = 1 ./ ((x-.3).^2 + .01) + 1 ./ ((x-.9).^2 + .04) - 6;

if nargout==2,

out1 = x; out2 = y;

else

out1 = y;

end

fplot('humps',[-1 2]); grid on, format long

% repasando ENL ....

raizp = fzero('humps',1.25), humps(raizp) % Metodo de Brent

raizp =

Página 4 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 25: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

1.29954968258482

ans =

0

raizn = fzero('humps',-0.25), humps(raizn) % Metodo de Brent

raizn =

-0.13161801809961

ans =

0

% Primitivas Matlab para integracion numerica:

% quad => Simpson adaptativo (NC cerrada 3 puntos (n=2) como formula de base)

% quad8 => Tambien adaptativo (NC cerrada 8 puntos (n=7) como formula de base)

% quadl => Lobatto adaptativo (Seudogaussina (fijos ambos extremos) como base)

% Todas son tecnicas adaptativas pero todas ellas basadas en formulas CERRADAS

quad('humps',-1,2)

ans =

26.34496050120123

quad8('humps',-1,2)

Warning: QUAD8 is obsolete. QUADL is its recommended replacement.

> In C:\MATLAB6p1\toolbox\matlab\funfun\quad8.m at line 35

ans =

26.34496024631924

quadl('humps',-1,2)

ans =

26.34496047137897

% trapz => Regla de los trapecios compuesta (Matlab)

x = -1:0.20:2; y = humps(x); trapz(x,y) % h=0.20

ans =

23.67372265612058

x = -1:0.05:2; y = humps(x); trapz(x,y) % h=0.05 (aproxima mejor y estable)

ans =

26.34455536552756

% E17

type f4_4

function y=f4_3(t) % OJO: Sólo con /t (en vez de ./t),

y=log(sin(t/4))+3*sin(4*t)./t; % aunque no provoca error, está mal

edit f4_4

fschange('c:\Documents and Settings\matap.AULA\Mis Documentos\f4_4.m');

clear f4_4

type f4_4

function y=f4_4(t) % OJO: Sólo con /t (en vez de ./t),

y=log(sin(t/4))+3*sin(4*t)./t; % aunque no provoca error, está mal

!copy f4_4.m f4_17.m

1 archivos copiados.

edit f4_17

fschange('c:\Documents and Settings\matap.AULA\Mis Documentos\f4_17.m');

clear f4_17

type f4_17

function y=f4_17(t) % OJO: Sólo con /t (en vez de ./t),

y=log(sin(t/4))+3*sin(4*t)./t; % aunque no provoca error, está mal

quad8('f4_17',0,4*pi)

Warning: Log of zero.

> In c:\Documents and Settings\matap.AULA\Mis Documentos\f4_17.m at line 2

In C:\MATLAB6p1\toolbox\matlab\funfun\quad8.m at line 57

Warning: Divide by zero.

> In c:\Documents and Settings\matap.AULA\Mis Documentos\f4_17.m at line 2

In C:\MATLAB6p1\toolbox\matlab\funfun\quad8.m at line 57

ans =

NaN

Página 5 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 26: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

2*(2*pi)*f4_17(2*pi) % Regla del punto medio simple

ans =

-5.878304635907296e-015

h=pi/16; x = h:h:4*pi; Ipm = h*sum(f4_17(x-h/2)), format short

Ipm =

-3.92305429827538

% Esta era la regla del punto medio compuesta (basada en formula abierta)

% E4

type p4_4

% Apartado a: Evaluación de f

h=pi/16;

x=h:h:2*pi;

dosene=length(x);

n=dosene/2;

% Una evaluación directa mediante quad8 presenta problemas tanto si se usa

% for k=1:dosene, f(k)=quad8('g',0,x(k)); end;

% como si se usa

% for k=1:dosene, f(k)=quad8('g',0.01,x(k)); end;

% Usaremos en su lugar una fórmula abierta de integración numérica,

% p.e. la del punto medio compuesta con nodos espaciados con h/2:

for k=1:dosene,

f(k)=h*sum(f4_4(x(1:k)-h/2));

end;

pause

% Apartado b: x_0=0, f_0=0 (también podría hacerse f_0=f_{2n})

x=0:h:2*pi-h; f=[0 f(1:dosene-1)];

c=fft(f);

a=zeros(1,dosene); a(1)=c(1)/dosene; a(dosene)=c(1+n)/dosene;

for k=1:n-1

a(2*k) = (c(1+k)+c(1+dosene-k))/dosene;

a(2*k+1)=i*(c(1+k)-c(1+dosene-k))/dosene;

end;

plot(x,f,'+-'); hold on;

x=0:0.01:2*pi-h;

phi=a(1)+a(dosene)*cos(n*x);

for k=1:n-1

phi=phi+a(2*k)*cos(k*x)+a(2*k+1)*sin(k*x);

end;

plot(x,phi,':'); hold off;

pause

% Apartado c: Estimación (bastante mala) del máximo de f

[fmaxest,indice]=max(phi); xmaxest=x(indice);

xmax=fzero('f4_4',0.5);

% Apartado a: Evaluación de f

h=pi/16;

x=h:h:2*pi;

dosene=length(x);

n=dosene/2;

Página 6 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 27: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

% Una evaluación directa mediante quad8 presenta problemas tanto si se usa

% for k=1:dosene, f(k)=quad8('g',0,x(k)); end;

% como si se usa

% for k=1:dosene, f(k)=quad8('g',0.01,x(k)); end;

% Usaremos en su lugar una fórmula abierta de integración numérica,

% p.e. la del punto medio compuesta con nodos espaciados con h/2:

for k=1:dosene,

f(k)=h*sum(f4_4(x(1:k)-h/2));

end;

size(f)

ans =

1 32

% Estimando f(0)...

type f4_4

function y=f4_4(t) % OJO: Sólo con /t (en vez de ./t),

y=log(sin(t/4))+3*sin(4*t)./t; % aunque no provoca error, está mal

syms x t real

limit( int( log(sin(t/4))+3*sin(4*t)/t ,0,x) ,x,0,'right')

ans =

0

% Apartado b: x_0=0, f_0=0 (también podría hacerse f_0=f_{2n})

x=0:h:2*pi-h; f=[0 f(1:dosene-1)];

c=fft(f);

a=zeros(1,dosene); a(1)=c(1)/dosene; a(dosene)=c(1+n)/dosene;

for k=1:n-1

a(2*k) = (c(1+k)+c(1+dosene-k))/dosene;

a(2*k+1)=i*(c(1+k)-c(1+dosene-k))/dosene;

end;

plot(x,f,'+-'); hold on;

x=0:0.01:2*pi-h;

phi=a(1)+a(dosene)*cos(n*x);

for k=1:n-1

phi=phi+a(2*k)*cos(k*x)+a(2*k+1)*sin(k*x);

end;

plot(x,phi,':'); hold off;

[fmaxest,indice]=max(phi), xmaxest=x(indice)

fmaxest =

3.71694660945382

indice =

69

xmaxest =

0.68000000000000

% valor maximo es fmaxest, maximo (abscisa) es xmaxest

% fmaxest NO es f4_4(xmaxest), sino int(f4_4,0,xmaxest)

xmax = fzero('f4_4',0.5) % otra estimacion de xmaxest

xmax =

0.68165380842987

% E12: Derivacion numerica

format long

type deriv

function y=deriv(F,x0,h)

y=(feval(F,x0+h)-feval(F,x0-h))/(2*h);

Página 7 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 28: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

deriv('cos',pi/2,1e-3)

ans =

-0.99999983333323

% Veamos que es peligroso bajar el h por debajo del h optimo

deriv('cos',pi/2,1e-10)

ans =

-1.00000008274037

deriv('cos',pi/2,1e-13)

ans =

-0.99920072216264

deriv('cos',pi/2,1e-16)

ans =

0

type f4_12

function y=f4_12(x)

y=(3.27*x.^3.*sqrt(2+sin(x)).*(0.23+x.^4))./(3.24+sin(0.23+x));

% f'(x0)=(f(x0-2h)-8f(x0-h)+8f(x0+h)-f(x0+2h))/(12h) + h^4f^5)(chi)/30

% segun pone en [Guerrero,03], pagina 87a

!copy deriv.m deriv4.m

1 archivos copiados.

edit deriv4.m

fschange('c:\Documents and Settings\matap.AULA\Mis Documentos\deriv4.m');

clear deriv4

type deriv4

function y=deriv4(F,x0,h)

y=(feval(F,x0-2*h)-8*feval(F,x0-h)+8*feval(F,x0+h)-feval(F,x0+2*h))/(12*h);

deriv('cos',pi/2,1e-3)

ans =

-0.99999983333323

deriv4('cos',pi/2,1e-3)

ans =

-0.99999999999982

% Aqui tambien es peligroso bajar el h por debajo del h optimo

deriv4('cos',pi/2,1e-10)

ans =

-1.00000008274037

deriv4('cos',pi/2,1e-13)

ans =

-0.99883064782110

deriv4('cos',pi/2,1e-16)

ans =

0.37007434154172

% Integracion numerica con NC cerradas

type ncotes5simple

function y=ncotes5simple(F,a,b)

h=(b-a)/4;

y=( 7*(feval(F,a) + feval(F,b)) ...

+32*(feval(F,a+h)+feval(F,a+3*h)) ...

+12*feval(F,a+2*h) ) /90*(b-a);

% ncotes5simple es NC cerrada (con n=4), conocida como formula de

% Boole, y ncotes5compuesta es su aplicacion en forma compuesta.

type ncotes5compuesta

function y=ncotes5compuesta(F,a,b,n)

h=(b-a)/n;

y=0;

for k=1:n

y=y+ncotes5simple(F,a+(k-1)*h,a+k*h);

Página 8 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 29: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

end

% El total N de subinvervalos en los que divides [a,b] es np,

% siendo p el cuarto argumento a ncotes5compuesta (i.e., el

% numero p de aplicaciones de la formula simple)

% E13

type f4_13

function y=f4_13(x)

y=(2+sin(pi*x))./(2+x+x.^2);

ncotes5simple('f4_13',2,5)

ans =

0.44874556854318

ncotes5compuesta('f4_13',2,5,10) % 10 aplicaciones, 40 subintervalos

ans =

0.42659227004952

% E16 (trapecios compuesta)

f4_16 = inline('1/sqrt((2-x^2)^2+x^2)')

f4_16 =

Inline function:

f4_16(x) = 1/sqrt((2-x^2)^2+x^2)

fplot(f4_16,[0 4]);

fplot('f4_16',[0 4]);

a = 0; b = 4; h = 0.02; N = (b - a)/h

N =

200

% 201 nodos en en intervalo [a,b]; cada n = 1 subintervalo aplico trapecios simple

fs = f4_16(a:h:b); % Asi NO, pues no hemos usado op elem a elem al definir f

??? Error using ==> inlineeval

Error in inline expression ==> 1/sqrt((2-x^2)^2+x^2)

??? Error using ==> ^

Matrix must be square.

Error in ==> C:\MATLAB6p1\toolbox\matlab\funfun\@inline\subsref.m

On line 25 ==> INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr,

INLINE_OBJ_.expr);

f4_16 = inline('1./sqrt((2-x.^2).^2+x.^2)')

f4_16 =

Inline function:

f4_16(x) = 1./sqrt((2-x.^2).^2+x.^2)

fplot(f4_16,[0 4]);

fs = f4_16(a:h:b); % Asi SI, pues ya hemos usado op elem a elem al definir f

format long

I = h/2*(fs(1)+2*sum(fs(2:end-1))+fs(end))

I =

1.49102190935772

I = h/2*(fs(1)+2*sum(fs(2:N))+fs(N+1)) % tambien vale

I =

1.49102190935772

trapz(a:h:b,fs)

ans =

1.49102190935772

edit

% EJERCICIO: Sabiendo que |E(f)|<=h^2(b-a)/12*max_{a<=chi<=b}|f''(chi)|,

% estima dicha cota y comprueba si se tienen o no 4 decimales correctos

% Tercera hora: PVI para EDOs

% y'(x)=f(x,y(x))=sen(x·y(x)), 0=a<=x<=b=5, y(0)=y(a)=alfa=3

dsolve('Dy=sin(t*y)','y(0)=3')

Warning: Explicit solution could not be found.

> In C:\MATLAB6p1\toolbox\symbolic\dsolve.m at line 326

ans =

[ empty sym ]

Página 9 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 30: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

% y(x_i) approx w_i

% [x,w] = ode45(f,[a b],alfa) es una tecnica adaptativa (tamaño paso h variable)

% [x,w] = ode23(f,[a b],alfa) es una tecnica adaptativa (tamaño paso h variable)

% [x,w] = euler1(f,a,b,alfa,n) es Taylor de orden 1 (tamaño paso fijo h = (b-a)/n)

% [x,w] = rk4(f,a,b,alfa,n) es RK clasic orden 4 (tamaño paso fijo h = (b-a)/n)

% En los dos ultimos casos, los nodos son {x_0,...,x_n} (i.e., n+1 puntos malla)

[xs,ws] = ode45(inline('sin(x*y)','x','y'),[0 5],3);

size(xs), size(ws)

ans =

45 1

ans =

45 1

plot(xs,ws(:,1))

find(xs==4) % para ver si ha pasado por el 4

ans =

[]

[xs,ws] = ode45(inline('sin(x*y)','x','y'),[0 4 5],3);

size(xs), size(ws)

ans =

3 1

ans =

3 1

plot(xs,ws(:,1))

[xs,ws] = ode45(inline('sin(x*y)','x','y'),0:0.1:5,3); % simula h=0.1 fijo con ode45

size(xs), size(ws)

ans =

51 1

ans =

51 1

% en este caso, n = 50

plot(xs,ws(:,1))

% Esquema para un sistema de EDOs de primer orden

% E3a

edit f5_3a

fschange('c:\Documents and Settings\matap.AULA\Mis Documentos\f5_3a.m');

clear f5_3a

type f5_3a

function du=f5_3a(t,u)

du=zeros(2,1);

du(1)=3*u(1)+2*u(2)-(2*t^2+1)*exp(2*t);

du(2)=4*u(1)+u(2)-(t^2+2*t-4)*exp(2*t);

[ts,ws] = ode45('f5_3a',[0 1],[1;1]);

size(ts), size(ws)

ans =

45 1

ans =

45 2

plot(ts,ws(:,1)) % para pintar las aproximaciones a u_1(t)

plot(ts,ws(:,2)) % para pintar las aproximaciones a u_2(t)

% Entrada/salida formateada: fprintf (esta vectorizado en Matlab) para tabla valores

fprintf('%6.4f %13.8f %13.8f\n',[ts';ws(:,1)';ws(:,2)'])

0.0000 1.00000000 1.00000000

0.0056 1.02276813 1.05072504

0.0112 1.04643309 1.10244230

0.0167 1.07101987 1.15517872

0.0223 1.09655421 1.20896200

0.0473 1.22326737 1.46346470

0.0723 1.37209788 1.74229811

0.0973 1.54594440 2.04855020

0.1223 1.74810076 2.38571218

0.1473 1.98228725 2.75771022

0.1723 2.25266699 3.16892259

Página 10 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 31: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

0.1973 2.56397856 3.62431312

0.2223 2.92160595 4.12950159

0.2473 3.33162976 4.69081552

0.2723 3.80085470 5.31531858

0.2973 4.33702651 6.01102866

0.3223 4.94894643 6.78703287

0.3473 5.64655543 7.65357248

0.3723 6.44098013 8.62209008

0.3973 7.34488816 9.70558638

0.4223 8.37267553 10.91880830

0.4473 9.54060519 12.27838838

0.4723 10.86688406 13.80292353

0.4973 12.37224547 15.51355920

0.5223 14.08025615 17.43429731

0.5473 16.01754432 19.59222557

0.5723 18.21392902 22.01764887

0.5973 20.70337522 24.74504670

0.6223 23.52449733 27.81357792

0.6473 26.72093500 31.26745807

0.6723 30.34156976 35.15617866

0.6973 34.44209262 39.53607787

0.7223 39.08583036 44.47116840

0.7473 44.34436509 50.03375891

0.7723 50.29789644 56.30481978

0.7973 57.03781621 63.37656169

0.8223 64.66806546 71.35379473

0.8473 73.30615591 80.35495224

0.8723 83.08377464 90.51270018

0.8973 94.15101531 101.97817330

0.9223 106.67860829 114.92320801

0.9417 117.53885628 126.12169350

0.9612 129.49600313 138.42995459

0.9806 142.66080714 151.95935924

1.0000 157.15569447 166.83297305

% E3b

edit f5_3b

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\f5_3b.m');

clear f5_3b

type f5_3b

function du=f5_3b(t,u)

du=zeros(2,1);

du(1)=u(2);

du(2)=exp(2*t)*sin(t)-2*u(1)+2*u(2);

[ts,ws] = ode45('f5_3b',[0 1],[-0.4;-0.6]);

size(ts), size(ws)

ans =

41 1

ans =

41 2

fprintf('%6.4f %13.8f %13.8f\n',[ts';ws(:,1)';ws(:,2)'])

0.0000 -0.40000000 -0.60000000

0.0250 -0.41512120 -0.60954227

0.0500 -0.43046877 -0.61808541

0.0750 -0.44601607 -0.62549619

0.1000 -0.46173297 -0.63163105

0.1250 -0.47758566 -0.63633573

0.1500 -0.49353644 -0.63944449

0.1750 -0.50954316 -0.64077917

0.2000 -0.52555905 -0.64014867

0.2250 -0.54153246 -0.63734848

0.2500 -0.55740654 -0.63215977

0.2750 -0.57311865 -0.62434825

Página 11 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 32: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

0.3000 -0.58860004 -0.61366361

0.3250 -0.60377560 -0.59983891

0.3500 -0.61856342 -0.58258950

0.3750 -0.63287408 -0.56161171

0.4000 -0.64661028 -0.53658221

0.4250 -0.65966649 -0.50715726

0.4500 -0.67192843 -0.47297145

0.4750 -0.68327224 -0.43363622

0.5000 -0.69356395 -0.38873908

0.5250 -0.70265911 -0.33784277

0.5500 -0.71040218 -0.28048379

0.5750 -0.71662546 -0.21617070

0.6000 -0.72114850 -0.14438325

0.6250 -0.72377764 -0.06457147

0.6500 -0.72430530 0.02384612

0.6750 -0.72250863 0.12148436

0.7000 -0.71814891 0.22899238

0.7250 -0.71097092 0.34705465

0.7500 -0.70070214 0.47639307

0.7750 -0.68705112 0.61776888

0.8000 -0.66970679 0.77198376

0.8250 -0.64833775 0.93988093

0.8500 -0.62259125 1.12234755

0.8750 -0.59209138 1.32031670

0.9000 -0.55643817 1.53476851

0.9250 -0.51520684 1.76673146

0.9500 -0.46794658 2.01728488

0.9750 -0.41417846 2.28756109

1.0000 -0.35339441 2.57874647

figure(1); plot(ts,ws(:,1)), grid % para pintar las aproximaciones a y(t)

figure(2); plot(ts,ws(:,2)), grid % para pintar las aproximaciones a y'(t)

fprintf('%6.4f %13.8f\n',[ts';ws(:,1)']) % con solo y (i.e., u1)

0.0000 -0.40000000

0.0250 -0.41512120

0.0500 -0.43046877

0.0750 -0.44601607

0.1000 -0.46173297

0.1250 -0.47758566

0.1500 -0.49353644

0.1750 -0.50954316

0.2000 -0.52555905

0.2250 -0.54153246

0.2500 -0.55740654

0.2750 -0.57311865

0.3000 -0.58860004

0.3250 -0.60377560

0.3500 -0.61856342

0.3750 -0.63287408

0.4000 -0.64661028

0.4250 -0.65966649

0.4500 -0.67192843

0.4750 -0.68327224

0.5000 -0.69356395

0.5250 -0.70265911

0.5500 -0.71040218

0.5750 -0.71662546

0.6000 -0.72114850

0.6250 -0.72377764

0.6500 -0.72430530

0.6750 -0.72250863

0.7000 -0.71814891

0.7250 -0.71097092

0.7500 -0.70070214

0.7750 -0.68705112

Página 12 de 14

Usuario
Highlight
Page 33: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

0.8000 -0.66970679

0.8250 -0.64833775

0.8500 -0.62259125

0.8750 -0.59209138

0.9000 -0.55643817

0.9250 -0.51520684

0.9500 -0.46794658

0.9750 -0.41417846

1.0000 -0.35339441

% E2

edit f5_2

edit

fschange('C:\Documents and Settings\matap.AULA\Mis documentos\f5_2.m');

clear f5_2

type f5_2

function du=f5_2(t,u)

du=zeros(3,1);

du(1)=-6*u(1)-3*u(2)+14*u(3);

du(2)= 4*u(1)+3*u(2)- 8*u(3);

du(3)=-2*u(1)- u(2)+ 5*u(3)+sin(t);

[ts,ws] = euler1('f5_2',0,10,[1;-1;0],1e4); % pues n = (b-a)/h = (10-0)/(1e-3)= 1e4

size(ts), size(ws)

ans =

10001 1

ans =

10001 3

plot(ts,ws) % para pintar x(t), y(t) y z(t) en una misma grafica

type euler1

function [x,y]=euler1(F,x0,xf,y0,n)

% function [x,y]=euler1(F,x0,xf,y0,n)

% Metodo de Euler para el problema de valores iniciales en EDO

% F nombre del fichero con la funcion a integrar.

% x0 punto inicial.

% xf punto final.

% n numero de subintervalos.

% y0 vector columna con los valores iniciales.

% x vector con los puntos intermedios donde se evalua.

% y matriz con los valores obtenidos en los puntos intermedios (x).

h=(xf-x0)/n; x=x0:h:xf;

y=y0;

for k=1:n,y(:,k+1)=y(:,k)+h*(feval(F,x(k),y(:,k)));end

y=y';x=x';

type rk4

function [x,y]=rk4(func,x0,xf,y0,n)

% Esta rutina implementa el metodo de Runge-Kutta usual de orden 4.

%function [x,y]=rk4(func,x0,xf,y0,n)

% Los parametros de llamada son:

% x0= escalar con el valor inicial de la x

% xf= escalar con el valor final de la x

% n = numero de saltos en donde se evalua y (equivale n=(xf-x0)/h donde

% h es el tamaño de paso.

% y0= vector columna con los valores iniciales.

h=(xf-x0)/n;

x=x0:h:xf;y=y0;

for k=1:n,

k1=feval(func,x(k),y(:,k));

k2=feval(func,x(k)+h/2,y(:,k)+h/2*k1);

k3=feval(func,x(k)+h/2,y(:,k)+h/2*k2);

k4=feval(func,x(k)+h,y(:,k)+h*k3);

y(:,k+1)=y(:,k)+(k1+k4+2*(k2+k3))*h/6;

Página 13 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Page 34: GuionN1to4

Guión N3+N4 (Pablo Guerrero) 2010/2011

end

x=x';y=y';

[ts,ws] = rk4('f5_2',0,10,[1;-1;0],1e3); % pues n = (b-a)/h = (10-0)/(1e-2)= 1e3

size(ts), size(ws)

ans =

1001 1

ans =

1001 3

plot(ts,ws) % para pintar x(t), y(t) y z(t) en una misma grafica

ws(end,1) % aproximacion para x(10)

ans =

3.234434568269429e+008

ws(end,2) % aproximacion para y(10)

ans =

-2.587547645911311e+008

ws(end,3) % aproximacion para z(10)

ans =

1.293773829871109e+008

ws(5,1) % aproximacion para x(5) (NO, asi no)

ans =

0.88091852130840

find(ts==5)

ans =

501

ws(501,1) % aproximacion para x(5) (SI, asi si)

ans =

1.468938412081753e+004

ws(501,2) % aproximacion para y(5) (SI, asi si)

ans =

-1.174997436541425e+004

ws(501,3) % aproximacion para z(5) (SI, asi si)

ans =

5.875324813745320e+003

% E1 (con 3 us) : n = (b - a)/h = (2 - 1)/(1e-3) = 1e3 = 1000

% E4 (con 3 us) : n = (b - a)/h = (3 - 1)/0.05 = 2/0.05 = 200/5 = 40

% E5 (con 3 us) : n = (b - a)/h = (2 - 1)/0.05 = 1/0.05 = 100/5 = 20

% y(2) se aproxima con ws(end,1)

% y''(1.95) se aproxima con ws(end-1,3)

% E6 (con 4 us) : h = (b - a)/n = (pi - 0)/n = pi/10 => n = 10

% y'''(pi) se aproxima con ws(end,4)

% y^(iv)(pi) se aproxima con ...

% ... 1/6*(-4*ws(end,1)-20*ws(end,2)-25*ws(end,3)-5*ws(end,4))

diary off

quit

Página 14 de 14

Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight
Usuario
Highlight