ivorra/curso-TN-TECI.pdf · b) Dibujar esta funcion en [−π,π]×[−2π,2π] con una paso de 0.1...
Transcript of ivorra/curso-TN-TECI.pdf · b) Dibujar esta funcion en [−π,π]×[−2π,2π] con una paso de 0.1...
TP 1 MAPLE - INTRODUCCION
MASTER T.E.C.I.
1 OPERACIONES DE BASE
> 1+3> 4-2> 3*5> 6/8> 3∧ 3> 10∧ (-6)> sqrt(5)> Pi> exp(0)> exp(2)> log(1)> cos(Pi)> sin(0)> tan((1/2)*pi)> abs(-5)> factorial(10)> round(5.5)> ceil(5.4)> floor(5.4)
2 FORMATO DE ESCRITURA
> 2+5 :> 2+5, 2+6> 2+5 ; 2+6 ; 2+7> Pi> evalf(Pi)> cos(.9898*Pi)> evalf(cos(.9898*Pi))> evalf[3](cos(.9898*Pi))
1
3 ASIGNACION DE VARIABLES
> X := 5> X+5> unassign(’X’)> X+5> restart :
4 MATRICES Y VECTORES
> Y := Vector([1, 2, 3, 4])> Y+Y> with(linalg)> MA := Matrix([[1, 2], [3, 4]])> MA2 := Matrix(2, 3)> MA3 := Matrix(1 .. 4, 1 .. 5, 5)> VD := [1, 2, 3]> MD := Matrix(1 .. 3, 1.3, VD, shape = diagonal)> det(MA)> trace(MA)> Transpose(MA)> with(LinearAlgebra) :> MA := Matrix([[1, 2], [3, 4]])> Eigenvalues(MA)> MA := Matrix([[1, 0], [0, 4]])> MatrixInverse(MA)> Y := Vector([1, 2])> MA.Y
5 COORDENADAS
> MA(1, 2)> MA(1, 2) := 3> MA(1 .. 2, 2) := 0
6 POLINOMIOS
> P := x ∧ 3-x ∧ 2+3> subs(x = 3, P)> fsolve(P = 0, x, complex)
7 FUNCIONES
> f1 := x -> (x∧ 2+1)> f1(3)
2
> f2 := (x, y)-> (x∧ 2+y∧ 2)> f(1, 1)
8 NUMEROS ALEATORIOS
> rand()> rand()
9 SALIDA TEXTUAL
> print(hola soy yo)> x := 10> print(el valor de ’x’ es, x)
10 SALIDA GRAFICA
> func := x-> cos(x)+sin(x)> plot(func)> plot(func(x), x = -5 .. 5)> func2d := (x, y) -> (exp(x)+log(y))> plot3d(func2d(x, y), x = -10 .. 10, y = 1 .. 5)
11 SALIDA EN FICHERO
> MA3 := matrix([[1, 2, 3], [2, 4, 6], [1.8, 3.1, 6.7]])> writedata(sol, MA3)
12 TESTS LOGICOS
> x := 5> evalb(x > 4)> evalb(x = 4)> evalb(x <= 4)> evalb(x <> 5)> y := 10> evalb(x = 5 and y = 10)> evalb(x = 5 or y = 11)> evalb(x = 5 xor y = 10)
13 PROGRAMACION
> x := 99> if x > 99 then print(’x’ es demasiado grande) else print(valor de ’x’ correcto) end if
3
> for i by 2 to 10 do print(la raiz de, i, es, evalf(sqrt(i))) end do> for n to 20 while n < 10 do print(el cuadrado de, n, es, evalf(n ∧ 2)) ; sol n := n∧ 2end do
14 EJERCICIOS
1) Escribir un ’script’ que permite calcular el factorial de un numero entero2) Dibujar las funciones f(x) = xn con n=1...10 y x en [-5,5]
4
TP 1 MATLAB - INTRODUCCION
MASTER T.E.C.I.
1 Operaciones basicas
2+57-23*82/53∧210∧(-5)1e-5sqrt(4)4∧(0.5)picos(pi)sin(pi/2)tan(pi)exp(0)log(1)inv(3)abs(-1)sign(-10)round(0.4)round(0.7)ceil(0.4)floor(0.4)factorial(10)
2 Formato de escritura
2+5 ;2+5,2+5,7-2,3*8format short1/3format long1/3
1
3 Asignacion de variables
x=5y=10x*yclear xclear all
4 Vectores, matrices y sus operaciones
4.1 Creacion
[1 2 3 4][1,2,3][1 ;2 ;3][1,2,3]’[1,2 ;3,4]M=[1,2 ;3,4]V=[1,2]MATO=ones(4,4)VECO1=ones(1,4)VECO2=ones(4,1)MATZ=zeros(4,4)MATD=diag([1,2,3,4])MATV=[]
4.2 Vectores y listas
V2=1 :10V3=1 :0.5 :3V4=10 :-1 :5V5=5 :-1 :10
4.3 Operaciones
M*V’det(M)trace(M)eig(M)norm(M,2)norm(V,1)norm(V,2)M2=[0,pi/2 ;pi,3*pi/2]cos(M2)2*V+3M2i=M2∧(-1)M2i*M2
2
M2i2=inv(M2)M2i2*M2M3=[1,2,3 ;4,5,6]size(M3)length(V)
5 Coordenadas
M3(2,2)M3(2,2)=55M3( :,1)M3(1, :)V3=[10 ;11]M3( :,1)=V3M3(1,1 :2)i=2V3(i)V3(end)V3(end-1)VECA=[1,2,3]VECB=[4,5,6]VECC=[VECA,VECB]
6 Polinomios
P=[-1,0,2,0,1] (A nivel de notaicon defeneriamos el polinomio −x4 + 2x2 + 1)polyval(P,0)polyval(P,1)roots(P)
7 Numeros aleatorios con distribucion normal
rand,rand,randrand(5,3)randperm(6)
8 Condiciones
8.1 Tests logicos
x=1(x>1)(x>=1)(x<5)(x<=10)
3
(x==1)(x =1)isa(x,’numeric’)y=’aaa’isa(y,’char’)isa(y,’logical’)isa((y>1),’logical’)exist xexist xx
8.2 Operaciones
x=1y=2(x==1)&(y==2)(x==1)|(y>2)xor((x==1),(y>2))
9 Outputs
9.1 Output textual
disp(’Hola’)MESS1=’El valor de x es : ’x=10MESS2=[MESS1 num2str(x)] ;disp(MESS2)
9.2 Output en ficheros
diary(’test.txt’)diary on1+1MESS1=’Se acabo !’ ;disp(MESS1)diary offresult=[1 3 10]fid = fopen([’results.txt’],’w’) ;fprintf(fid,’Final point :\n’) ;fprintf(fid,’0.12f\n ’,result) ;fprintf(fid,’or :\n’) ;fprintf(fid,[num2str(result) ’\n ’],result) ;fclose(fid) ;
4
9.3 Output grafico
9.3.1 En dimension 1 :
dat=1 :.1 :10 ;resdat=cos(dat) ;figure(1)clfplot(dat,resdat)grid onxlabel(’Data’)ylabel(’Result’)dat2=1 :.1 :10 ;resdat2=sin(dat2) ;figure(2)clfsubplot(2,1,1)plot(dat,resdat,’color’,[1 0 0])title(’Cos’)subplot(2,1,2)plot(dat2,resdat2,’color’,[0 1 0],’linewidth’,3)title(’Sin’)figure(3)clfhold onplot(dat,resdat,’color’,[1 0 0])plot(dat2,resdat2,’color’,[0 1 0],’linewidth’,3)Legend(’Cos’,’Sin’)saveas(gcf,’test’,’jpg’)close all
9.3.2 En dimension 2 :
x=-20 :1 :20 ;y=-30 :1 :30 ;A=rand(length(x),length(y)) ;[Xgrid,Ygrid]=meshgrid(x,y) ;figure(1)clfsurface(Xgrid,Ygrid,A’)xlabel(’xdata’)ylabel(’ydata’)zlabel(’result’)view(45,45)
5
10 Programacion
10.1 Creacion de script con Algunos comandos utiles
Nota : Se tiene que crear en un script a parte :
clcdisp(’Hola’)x=10 ;disp([’x vale ’ num2str(x)])x=x+1 ;disp([’Y ahorra x vale ’ num2str(x)])disp([])tica=input(’Entrar el valor de a : ’) ;atime=ceil(toc) ;disp([’a vale ’ num2str(a) ’ y has tardado ’ num2str(atime) ’ segundos en responder’])ticpause(.5)tocAA=[ 1 2 3 ...4 5 6 7 8]disp(’Escritura en el DD’)fid = fopen([’results.txt’],’w’) ;fprintf(fid,’Vector AA : \ n’) ;fprintf(fid,’0.12f \ n’,AA’) ;fclose(fid) ;disp(’Lectura en el DD’)fid = fopen([’results.txt’],’r’) ;text = fgets(fid)AAR(1) = str2num(fgets(fid))AAR(2) = str2num(fgets(fid))afin = fscanf(fid, ’g’)AAR=[AAR afin’]fclose(fid) ;pause
10.2 El uso del ’if ’
Nota : Se tiene que crear en un script a parte :
clcdisp(’Vamos a ver si X es mas grande que Y’)x=input(’Valor de x : ’) ;y=input(’Valor de y : ’) ;disp([’x vale ’ num2str(x)])disp([’y vale ’ num2str(y)])
6
if (x>y)disp([’x mas grande que y ’])elseif (x==y)disp([’x igual a y ’])elsedisp([’x mas pequeño que y ’])end
10.3 El uso del ’for’
Nota : Se tiene que crear en un script a parte :
clcdisp(’Vamos a calcular la raiz de los diez priemros numeros enteros y lso guardamos enuna lista’)lr=[] ; La lista es vaciafor i=1 :1 :10lr(i)=sqrt(i) ;disp([’la raiz de ’ num2str(i) ’ es ’ num2str(lr(i))])end
10.4 El uso del ’while’
Nota : Se tiene que crear en un script a parte :
clcdisp(’Vamos a ver cual es el primer numero entero mas grande o igual que sqrt(99)’)NMG=1 ;while(NMG<sqrt(100))NMG=NMG+1 ;endresp=[’ sqrt(100) vale ’ num2str( sqrt(100))...’ yel primer numero entero mas grande o igual es ’ num2str(NMG)] ;disp(resp)
10.5 Creacion de una funcion
Nota : Se tiene que crear en un script a parte :
function de R∧2 end R (x,y)-> x∧2+y∧3function [J]=mifunc(x,y)J=x∧2+y∧3 ;end
Nota : Se tiene que ir al workspace :
7
mifunc(2,3)
Nota : Se tiene que crear en un script a parte :
function de R end R∧2 (x)-> (sum(x), norm(x,2))function [J,N]=mifunc2(x)N=norm(x,2)J=sum(x)end
Nota : Se tiene que ir al workspace :
[J,N]=mifunc2(1)
11 Ejercicios
11.1 Ejercicio 1 :
a) Programar una funcion f(x, y) = cos(x) + 2sin(y)b) Dibujar esta funcion en [−π, π] × [−2π, 2π] con una paso de 0.1
11.2 Ejercicio 2 :
Progamar una funcion nprimo(n) que calcula el n-isemo numero primo verificando si laentrada ’n’ dada es un numero natural, sino devuelve un mensaje de error ’n no es unnumero natural’.
8
TP 2 MAPLE - INTERPOLACION
MASTER T.E.C.I.
1 Comandos Maple para la interpolacion numerica
1.1 Interpolacion en 1D
with(CurveFitting) ;with(plots) ;tiempo := [0., 3., 25., 54., 63., 82., 97., 100.] ;valor := [0., 5., 20., 30., 20., 10., 50., 60.] ;pointplot(tiempo, valor) ;tiempoint := [seq(0 .. 100, 1)] ;
interpval := ArrayInterpolation(tiempo, valor, tiempoint, method = linear) ;pointplot(tiempointerp, interpval) ;
interpval := ArrayInterpolation(tiempo, valor, tiempoint, method = nearest) ;pointplot(tiempointerp, interpval) ;
interpval := ArrayInterpolation(tiempo, valor, tiempoint, method = cubic) ;pointplot(tiempointerp, interpval) ;
interpval := ArrayInterpolation(tiempo, valor, tiempoint, method = spline) ;pointplot(tiempointerp, interpval) ;
1.2 Interpolacion en 2D
restart ;with(CurveFitting) ;with(plots) ;f := (a, b) -> cos(a) - cos(-b)plot3d(f, 0 .. 2*Pi, 0 .. Pi, axes = normal) ;
xde := [seq(0 .. 6, 6/49)] ;yde := [seq(0 .. 3.14, 3.14*(1/49))] ;zde := Matrix(50, 50,(a, b) -> f(xde[a], yde[b])) ;pointplot3d([seq(seq([xde[i], yde[j], zde[i, j]], j = 1 .. 50), i = 1 .. 50)], axes = normal) ;
1
xd := [0, 1.5, 3.14, 5, 6] ;yd := [0, 1, 2, 3.14] ;zd := Matrix(5, 4, (a, b) ->f(xd[a], yd[b])) ;pointplot3d([seq(seq([xd[i], yd[j], zd[i, j]], j = 1 .. 4), i = 1 .. 5)], axes = normal) ;
npt := 50 ;xint := Matrix(npt, npt,(i, j) -> (i-1)*max(xd)/(npt-1) ) ;yint := Matrix(npt, npt, (i, j) -> (j-1)*max(yd)/(npt-1) ) ;pinte := ArrayTools[Concatenate](3, xint, yint) ;
datai := ArrayInterpolation([xd, yd], zd, pinte, method = linear) ;matrixplot(Matrix(datai), axes = normal) ;linearM := Matrix(50, 50, (a, b) -> datai(a, b)) ;pointplot3d([seq(seq([xde[i], yde[j], linearM[i, j]], j = 1 .. 50), i = 1 .. 50)], axes = normal) ;
datai := ArrayInterpolation([xd, yd], zd, pinte, method = nearest) ;matrixplot(Matrix(datai), axes = normal) ;
datai := ArrayInterpolation([xd, yd], zd, pinte, method = cubic) ;matrixplot(Matrix(datai), axes = normal) ;cubicM := Matrix(50, 50, (a, b) -> datai(a, b)) ;pointplot3d([seq(seq([xde[i], yde[j], cubicM[i, j]], j = 1 .. 50), i = 1 .. 50)], axes = normal) ;
datai := ArrayInterpolation([xd, yd], zd, pinte, method = spline) ;matrixplot(Matrix(datai), axes = normal) ;splineM := Matrix(50, 50, (a, b) -> datai(a, b)) ;pointplot3d([seq(seq([xde[i], yde[j], splineM[i, j]], j = 1 .. 50), i = 1 .. 50)], axes = normal) ;
norm(zde, 2) ;norm(cubicM-splineM, 2) ;norm(linearM, 2) ;norm(cubicM, 2) ;norm(zde-cubicM, 2) ;norm(zde-linearM, 2) ;
2 Comandos simbolicos
restart :with(CurveFitting) ;with(plots) ;aint := [0, 1, 5, 10] ;bint := [1, 5, 2, 5] ;pointplot(aint, bint) ;
Polyint := PolynomialInterpolation(aint, bint, z) ;Polyint := PolynomialInterpolation(aint, bint, z, form = Lagrange) ;
2
Polyint := PolynomialInterpolation(aint, bint, z, form = Newton) ;plot(Polyint, z = 0 .. 10) ;
splint :=Spline(aint, bint, z) ;plot(splint, z = 0 .. 10) ;
3 Ejercicios
a) Calcular el polinomio de interpolacion de Langrage asociado a la tabla de datos si-guiente :
x -5 -2 0 3 10 20y 0 5 0 -3 -1 3
y dibujar su grafico en el intervalo[-5,20].
b) Calcular una spline asociada a los datos de la parte a) y dibujar su grafico en el inter-valo [-5,20].
c) Consideramos los siguientes puntos de interpolacion : Σ = {−5,−4,−3,−2,−1, 0, 1,
2, 3, ...20}. Calcular los valores interpolados en Σ considerando los datos de la parte a)y un metodo de interpolacion cubica. Rerpesentar graficamente estos puntos.
3
TP 2 MATLAB - INTERPOLACION
MASTER T.E.C.I.
1 Comandos Matlab para la interpolacion
1.1 Interpolacion en 1D
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=[-1 5 8 10] ;y=[0 6 2 5] ;k=1 ;
figure(k)clfplot(x,y,’o’)title(’puntos de interpolacion’)k=k+1 ;
figure(k)clfhold onplot(x,y,’o’)plot(x,y,’r’)title(’puntos de interpolacion’)
xint=-1 :.1 :10yint = interp1(x,y,xint)yint2 = interp1(x,y,xint,’lineal’)norm(yint-yint2,2)k=k+1 ;
figure(k)clfplot(xint,yint,’o’)
1
title(’puntos de interpolados’)
k=k+1figure(k)clfhold onplot(xint,yint,’go’)plot(xint,yint,’r’)plot(x,y,’s’)title(’Interpolacion lineal’)
yint3 = interp1(x,y,xint,’nearest’)k=k+1 ;figure(k)clfhold onplot(xint,yint3,’go’)plot(xint,yint3,’r’)plot(x,y,’s’)title(’Interpolacion PWC’)
yint3 = interp1(x,y,xint,’cubic’)k=k+1 ;figure(k)clfhold onplot(xint,yint3,’go’)plot(xint,yint3,’r’)plot(x,y,’s’)title(’Interpolacion cubic (Hermite)’)
yint3 = interp1(x,y,xint,’spline’)k=k+1 ;figure(k)clfhold onplot(xint,yint3,’go’)plot(xint,yint3,’r’)plot(x,y,’s’)title(’Interpolacion cubic (Spline)’)
yint3 = spline(x,y,xint)k=k+1 ;figure(k)clfhold onplot(xint,yint3,’go’)
2
plot(xint,yint3,’r’)plot(x,y,’s’)title(’Interpolacion cubic (Spline - funcion spline)’)
yint3 = pchip(x,y,xint)k=k+1 ;figure(k)clfhold onplot(xint,yint3,’go’)plot(xint,yint3,’r’)plot(x,y,’s’)title(’Interpolacion cubic (Hermit - funcion pchip)’)
1.2 Interpolacion en 2D
1.2.1 Datos uniformes
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=-10 :5 :10 ;y=-20 :5 :20 ;[xx,yy]=meshgrid(y,x) ;
for ii=1 :length(x)for jj=1 :length(y)zz(ii,jj)=cos(x(ii))+sin(y(jj)) ;endend
k=1 ;figure(k)clfhold onsurface(xx,yy,zz)title(’Original data’)view([45 45])axis(’tight’)plot3(xx,yy,zz,’oy’)
xi=-10 :.5 :10 ;yi=-20 :.5 :20 ;[xxi,yyi]=meshgrid(yi,xi) ;
3
zzi = interp2(xx,yy,zz,xxi,yyi,’nearest’) ;k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi)title(’Nearest interpolation’)view([45 45])axis(’tight’)plot3(xx,yy,zz,’oy’)
zzi = interp2(xx,yy,zz,xxi,yyi,’linear’) ;k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi)title(’Linear interpolation’)view([45 45])axis(’tight’)plot3(xx,yy,zz,’oy’)
zzi = interp2(xx,yy,zz,xxi,yyi,’cubic’) ;k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi)title(’Hermit interpolation’)view([45 45])axis(’tight’)plot3(xx,yy,zz,’oy’)
zzi = interp2(xx,yy,zz,xxi,yyi,’spline’) ;k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi)title(’Spline interpolation’)view([45 45])axis(’tight’)plot3(xx,yy,zz,’oy’)
4
1.2.2 Datos no uniformes
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=[1 5 15 -9 -10 8 7 -8] ;y=[-5 3 8 -3 10 -10 5 2] ;z=[1 5 3 7 10 4 8 9] ;k=1 ;
figure(k)clfhold onplot3(x,y,z,’ok’)title(’Original data’)view([45 45])axis(’tight’)
xi=min(x) :((max(x)-min(x))/99) :max(x) ;yi=min(y) :((max(y)-min(y))/99) :max(y) ;[xxi,yyi]=meshgrid(yi,xi) ;
zzi = griddata(x,y,z,xxi,yyi,’nearest’) ;k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi,’Edgecolor’,’none’)title(’Linear interpolation’)view([45 45])axis(’tight’)plot3(x,y,z,’ok’)
zzi = griddata(x,y,z,xxi,yyi,’linear’) ;k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi,’Edgecolor’,’none’)title(’Linear interpolation’)view([45 45])axis(’tight’)plot3(x,y,z,’ok’)
zzi = griddata(x,y,z,xxi,yyi,’cubic’) ;
5
k=k+1 ;figure(k)clfhold onsurface(xxi,yyi,zzi,’Edgecolor’,’none’)title(’Cubic interpolation’)view([45 45])axis(’tight’)plot3(x,y,z,’ok’)
1.3 Interpolacion en 3D
1.3.1 Datos uniformes
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=-10 :5 :10 ;y=-20 :5 :20 ;z=-10 :5 :5 ;[xg,yg,zg] = meshgrid(y,x,z) ;xi=-10 :1 :10 ;yi=-20 :1 :20 ;zi=-10 :1 :5 ;[xgi,ygi,zgi] = meshgrid(yi,xi,zi) ;
for ii=1 :length(x)for jj=1 :length(y)for kk=1 :length(z)dat(ii,jj,kk)=x(ii)∧2+y(jj)∧2+z(kk)∧2 ;endendend
dati = interp3(xg,yg,zg,dat,xgi,ygi,zgi,’cubic’) ;figure(1)hold onslice(xg,yg,zg,dat,[-20,0],[0,10],[-10,0]), shading flatview([45 45])title(’Original data’)figure(2)hold onslice(xgi,ygi,zgi,dati,[-20,0],[0,10],[-10,0]), shading flatview([45 45])title(’Hermit interpolation’)
6
1.3.2 Datos no uniformes
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx= [-9 5 9 0 4 3 6 8] ;y= [-1 2 -5 8 9 1 7 -8 ] ;z= [1 0 5 9 3 -6 -5 -9] ;dat=[0 1 2 5 -5 6 3 4] ;
xi=-10 :1 :10 ;yi=-20 :1 :20 ;zi=-10 :1 :5 ;[xgi,ygi,zgi] = meshgrid(yi,xi,zi) ;
dati = griddata3(x,y,z,dat,xgi,ygi,zgi,’linear’) ;figure(1)hold onslice(xgi,ygi,zgi,dati,[-20 :3 :20],[-10 :3 :10],[-10 :3 :5]), shading flatplot3(x,y,z,’o’)view([45 45])title(’Linear interpolation’)
1.3.3 Interpolacion en dimensiones superiores
1.3.4 Datos uniformes
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=-10 :10 :10 ;y=-20 :10 :20 ;z=-10 :10 :10 ;k=-30 :10 :30 ;[xg,yg,zg,kg] = ndgrid(x,y,z,k) ;xi=-10 :5 :10 ;yi=-20 :5 :20 ;zi=-10 :5 :10 ;ki=-30 :5 :30 ;[xgi,ygi,zgi,kgi] = ndgrid(xi,yi,zi,ki) ;
for ii=1 :length(x)for jj=1 :length(y)for kk=1 :length(z)
7
for ll=1 :length(k)dat(ii,jj,kk,ll)=x(ii)∧2+y(jj)∧2+z(kk)∧2+k(kk)∧2 ;endendendend
dati = interpn(xg,yg,zg,kg,dat,xgi,ygi,zgi,kgi,’cubic’) ;figure(1)hold onplot(x,dat( :,1,1,1),’b’)plot(xi,dati( :,1,1,1),’r’)title(’Comparison of some data’)legend(’Ori.’,’Interp.’)
1.3.5 Datos no uniformes
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx= [-9 5 9 0 4 3 6 8] ;y= [-1 2 -5 8 9 1 7 -8 ] ;z= [1 0 5 9 3 -6 -5 -9] ;k= [9 8 5 -9 -3 7 -1 -10] ;dat=[0 1 2 5 -5 6 3 4] ;xi=-10 :1 :10 ;yi=-20 :1 :20 ;zi=-10 :1 :5 ;ki=-10 :1 :10 ;[xgi,ygi,zgi,kgi] = ndgrid(xi,yi,zi,ki) ;
XO = [x( :),y( :),z( :),k( :)] ;XI = [xgi( :),ygi( :),zgi( :),kgi( :)] ;dati = griddatan(XO,dat’,XI,’linear’) ;datim=reshape(dati, size(ygi)) ;
2 Ejercicios
a) Programar una funcion sol = minterp(x, y, t,met), donde x representa los puntos demediciones, y los datos y t los puntos de inteprolacion, que devuelve en funcion de lacadena met :– Si met=’linear’ : sol son los datos obtenidos por interpolacion lineal (con la formula
vista en clase) de (x, y) en los puntos de interpolacion t.
8
– Si met=’lagrange’ : sol son los datos obtenidos por interpolacion de polinomios delagrange (con la formula vista en clase) de (x, y) en los puntos de interpolacion t.
b) Aplicar esta minnterp considerando los dos metodos (’linear’ y ’lagrange’) a los datossiguientes
x -10 -3 0 2 5 10y -5 0 1 5 2 5
y dibujar las graficas de los datos interpolados.
9
TP 3 MAPLE - Derivacion
MASTER T.E.C.I.
1 Comandos MAPLE
1.1 Derivacion explicita
f :=(x)-> cos(x2) ;g := diff(f(x), x) ;diff(f(x), x$2) ;g(2) ;h := diff(g, x) ;diff(f(x), x$3) ;plot(f(x), x = -Pi .. Pi) ;plot(g(x), x = -Pi .. Pi) ;plot(h(x), x = -Pi .. Pi) ;
f2 := (x, y) -> x2 ∗ (x2 + y3)plot3d(f2(x, y), x = -1..1, y = -1..1) ;diff(f2(x, y, z), x) ;diff(f2(x, y, z), x, y) ;diff(f2(x, y, z), y) ;diff(f2(x, y, z), y, x) ;diff(f2(x, y, z), y$2) ;diff(f2(x, y, z), x$1, y$2) ;diff(f2(x, y, z), x, y, x) ;
with(VectorCalculus) ;grad := Gradient(f2(x, y), [x, y]) ;grad[1] ;grad[2] ;with(plots) ;gradplot(f2(x, y), x = -1..1, y = -1..1) ;
hess := Hessian(f2(x, y), [x, y]) ;hess[1, 1] ;hess[1, 2] ;hess[2, 1] ;hess[2, 2] ;
1
1.2 Derivacion implicita
F := (x, y) -> x2 + y2 − 1 ;with(plots, implicitplot) ;implicitplot(F(x, y) = 0, x =-1..1, y = -1..1) ;implicitdiff(F(x, y) = 0, y, x) ;implicitdiff(F(x, y) = 0, y, $ (x, 2)) ;implicitdiff(F(x, y) = 0, y, x, x) ;
F2 := (x, y, z) -> cos(x2) + y4 + sin(z2) − 1 ;implicitplot3d(F2(x, y, z) = 0, x = -5..5, y = -5..5, z = -5..5) ;implicitdiff(F2(x, y, z) = 0, y, x) ;implicitdiff(F2(x, y, z) = 0, y, x$2, z$2) ;
2 Ejercicios
a) Calcular :• d
dx(cos(x5 + exp(x)) ∗ (x2 − sin(x)))
• d4
dx4 (√
x1+x2 )
• ∂∂y
(x ∗√
y + 5 + cos(x ∗ y))
• ∂∂y
∂∂z
(x ∗ y ∗ z + ln(x2 + y3 + z2))
• ∂2
∂x2
∂3
∂z3 (cos(x ∗ y ∗ z) ∗ (x2 + exp(z))
b) Calcular el vector gradiente y la Matriz Hessiana de f(x, y, z) = exp(cos(x2 ∗ y)) ∗ z2.
2
TP 3 MATLAB - Derivacion
MASTER T.E.C.I.
1 Metodos de Taylor
1.1 Derivacion en dim 1 :
Nota : Se tiene que crear en un script a parte la funcion :
function J=func1(x)J=sin(cos(x)*2*pi) ;end
Nota : Se tiene que crear en un script a parte la funcion :
function J=func1d(x)J=cos(cos(x)*2*pi)*2*pi*(-sin(x)) ;end
Nota : Se tiene que crear en un script a parte la funcion :
function J=func1ds(x)J=2*pi*(sin(cos(x)*2*pi)*sin(x)*2*pi*(-sin(x))-(cos(x))*cos(cos(x)*2*pi))end
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=0 :.1 :2*pi ;y=func1(x) ;
for i=1 :length(x)yd(i)=func1d(x(i)) ;end
figure(1)clf
1
hold onplot(x,y,’r’)plot(x,yd,’b’)axis tight
disp(’Calculo de la derivada primera mediante una aproximacion de taylor de un solopunto’)derivt1=[] ;eps=1e-6 ;
for i=1 :length(x)yr=func1(x(i)) ;yd=func1(x(i)+eps) ;derivt1(i)=(yd-yr)/eps ;end
figure(1)plot(x,derivt1,’ :g’)errt1=norm(derivt1-yd,2) ;disp([’Error Taylor 1 : ’, num2str(errt1)])
disp(’Calculo de la derivada primera mediante una aproximacion de taylor centrada’)derivt2=[] ;eps=1e-6 ;
for i=1 :length(x)yp=func1(x(i)+eps) ;ym=func1(x(i)-eps) ;derivt2(i)=(yp-ym)/2*eps ;end
errt2=norm(derivt2-yd,2) ;disp([’Error Taylor 2 : ’, num2str(errt2)])
for i=1 :length(x)yds(i)=func1ds(x(i)) ;end
figure(2)clfhold onplot(x,y,’r’)plot(x,yds,’b’)axis tight
disp(’Calculo de la derivada seguna mediante una aproximacion de taylor’)derivts=[] ;
2
eps=1e-6 ;
for i=1 :length(x)yr=func1(x(i)) ;yp=func1(x(i)+eps) ;ym=func1(x(i)-eps) ;derivts(i)=(yp-2*yr+ym)/(eps)∧2 ;end
figure(2)plot(x,derivts,’ :g’)errts=norm(derivts-yds,2) ;disp([’Error Taylor 1 : ’, num2str(errts)])
1.2 Derivacion en dim 2 :
Nota : Se tiene que crear en un script a parte la funcion :
function J=func2(x)J=x(1)∧2+sin(x(2)) ;end
Nota : Se tiene que crear en un script a parte la funcion :
function grad=func2(x)grad(1)=2*x(1) ;grad(2)=cos(x(2)) ;end
Nota : Se tiene que crear en un script a parte la funcion :
function hess=func2(x)hess(1)=2 ;hess(2)=0 ;hess(3)=0 ;hess(4)=-sin(x(2)) ;end
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=-2 :.5 :2 ;y=0 :.5 :2*pi ;[xgrid,ygrid]=meshgrid(x,y) ;
3
for i=1 :length(x)for j=1 :length(y)z(j,i)=func2([xgrid(j,i),ygrid(j,i)]) ;grex=func2g([xgrid(j,i),ygrid(j,i)]) ;hsex=func2h([xgrid(j,i),ygrid(j,i)]) ;gradx(j,i)=grex(1) ;grady(j,i)=grex(2) ;hessxx(j,i)=hsex(1) ;hessxy(j,i)=hsex(2) ;hessyx(j,i)=hsex(3) ;hessyy(j,i)=hsex(4) ;endend
figure(1)clfhold onsurface(xgrid,ygrid,z)contour(xgrid,ygrid,z)view([45,45])quiver(x,y,gradx,grady)title(’Gradiente exacto’)
disp(’Calculo del gradiente mediante una aproximacion de taylor centrada’)epsi=1e-6
for i=1 :length(x)for j=1 :length(y)zpx=func2([xgrid(j,i)+epsi,ygrid(j,i)]) ;zmx=func2([xgrid(j,i)-epsi,ygrid(j,i)]) ;gradtx(j,i)=(zpx-zmx)/(2*epsi) ;zpy=func2([xgrid(j,i),ygrid(j,i)+epsi]) ;zmy=func2([xgrid(j,i),ygrid(j,i)-epsi]) ;gradty(j,i)=(zpy-zmy)/(2*epsi) ;endend
figure(2)clfhold onsurface(xgrid,ygrid,z)contour(xgrid,ygrid,z)view([45,45])quiver(x,y,gradtx,gradty)title(’Gradiente aprox.’)
disp([’Errores en el gradiente : ’])
4
norm(gradx-gradtx,2)norm(grady-gradty,2)
disp(’Calculo de la hessiana mediante una aproximacion de taylor centrada’)
for i=1 :length(x)for j=1 :length(y)zpr=func2([xgrid(j,i),ygrid(j,i)]) ;zpx=func2([xgrid(j,i)+epsi,ygrid(j,i)]) ;zmx=func2([xgrid(j,i)-epsi,ygrid(j,i)]) ;hstxx(j,i)=(zpx+zmx-2*zpr)/(epsi)∧2 ;zpr=func2([xgrid(j,i),ygrid(j,i)]) ;zpx=func2([xgrid(j,i),ygrid(j,i)+epsi]) ;zmx=func2([xgrid(j,i),ygrid(j,i)-epsi]) ;hstyy(j,i)=(zpx+zmx-2*zpr)/(epsi)∧2 ;zpx1=func2([xgrid(j,i)+epsi,ygrid(j,i)+epsi]) ;zmx1=func2([xgrid(j,i)-epsi,ygrid(j,i)+epsi]) ;zpx2=func2([xgrid(j,i)+epsi,ygrid(j,i)-epsi]) ;zmx2=func2([xgrid(j,i)-epsi,ygrid(j,i)-epsi]) ;hstyx(j,i)=(((zpx1-zmx1)/(2*epsi))-((zpx2-zmx2)/(2*epsi)))/(2*epsi) ;hstxy(j,i)=(((zpx1-zpx2)/(2*epsi))-((zmx1-zmx2)/(2*epsi)))/(2*epsi) ;endend
disp([’Errores en la Hessiana : ’])norm(hessxx-hstxx,2)norm(hessyy-hstyy,2)norm(hessxy-hstxy,2)norm(hessyx-hstyx,2)
2 Ejercicios
a) Crear una funcion en mifunc(x, y, z) = exp(−x2) + cos(y/10) − sin(z).
b) Crear una funcion migradex(x, y, z) que devuelve el gradiente exacto de mifunc enel punto (x,y,z).
c) Crear una funcion migradtl(x, y, z) script que permite calcular el gradiente aproxi-mado de mifunc en el punto (x,y,z) usando una proximacion de Taylor centrada conuna perturbacion de ǫ = 10
−6.
d) Crear un script que calcule el gradiente de mifunc en los puntos (0,0,0) y (-2,1,3)usando migradex y migradtl.
5
TP 4 MAPLE - Integracion
MASTER T.E.C.I.
1 Comandos MAPLE
1.1 Integracion en 1D
f := (x) -> x2+ exp(x) ;
plot(f(x), x = -1 .. 1) ;int(f(x), x) ;
int(f(x), x = -1 .. 1) ;int(exp(-x), x = 0 .. infinity) ;int(exp(-x), x = a .. b) ;a := 1 ;b := 2 ;int(exp(-x), x = a .. b) ;int(exp(cos(x))*ln(x), x) ;int(exp(cos(x)), x = -1 .. 1) ;evalf(int(exp(cos(x)), x = -1 .. 1)) ;int(exp(cos(x)), x = -1 .. 1, numeric) ;int(f(x), x = -1.5 .. 2.95) ;int(f(x), x = -1.5 .. 2.95, numeric = false) ;int(f(x), x = 2.95 .. -1.5) ;
Ejemplo de calculo de los coeficientes αl vistos en clases necesarios para obtener la formulade Newton-côtes de orden Q = 2 :
int((s-1)*(s-2)/((0-1)*(0-2)), s = 0 .. 2) ;int((s-0)*(s-2)/((1-0)*(1-2)), s = 0 .. 2) ;int((s-0)*(s-1)/((2-0)*(2-1)), s = 0 .. 2) ;
1.2 Integracion en dimensiones superiores
1.2.1 Caso 2D
g := (x, y) -> y ∗ x + y2 ;plot3d(g(x, y), x = -1 .. 1, y = -1 .. 1) ;int(g(x, y), x) ;int(g(x, y), y) ;
1
int(g(x, y), x, y) ;int(g(x, y), x = -1 .. 1, y = -1 .. 1) ;int(g(x, y), x = -1 .. 1, y = -1 .. 1, numeric) ;int(exp(cos(x)*y), x = -1 .. 1, y = -2 .. 2) ;evalf(int(exp(cos(x)*y), x = -1 .. 1, y = -2 .. 2)) ;int(exp(cos(x+y)), x, y) ;int(exp(cos(x+y)), x = -5 .. 10, y = 3 .. 8) ;int(exp(cos(x+y)), x = -5 .. 10, y = 3 .. 8, numeric) ;
1.2.2 Caso 3D
h := (x, y, z) -> x2+ exp(y) + sqrt(z ∗ x) ;
int(h(x, y, z), x, y, z) ;int(h(x, y, z), x = 0 .. 5, y = -5 .. 0, z = 2 .. 8) ;int(h(x, y, z), x = 0 .. 5, y = -5 .. 0, z = 2 .. 8, numeric) ;
2 Ejercicios
a) Calcular :
•∫
exp(√
x + 3) dx
•∫
5
0 log(x2+ x) dx (dar la solucion exacta y una aproximacion numerica).
•∫
∞
−∞
exp(−x2) dx
•∫ ∫
log(y) ∗ y ∗ x dydx
•∫
8
2
∫
5
0
√y + x ∗ x dydx (dar la solucion exacta y una aproximacion numerica).
b) Calcular los coeficientes αl vistos en clases necesarios para obtener la formula deNewton-côtes de orden Q = 3.
2
TP 4 MATLAB - Integracion
MASTER T.E.C.I.
1 Metodos de Newton-Cotes
1.1 Integracion en 1D : Formulas de NC de orden 0, 1 y 2
Nota : Se tiene que crear en un script a parte la funcion :
function j=func2tp4(x)j=x∧2 ;endNota : Se tiene que crear en un script a parte la funcion :
function j=func2tp4(x)j=x∧3 ;endNota : Se tiene que crear en un script a parte la funcion :
function j=func3tp4(x)j=exp(x) ;endNota : Se tiene que crear en un script a parte la funcion :
function j=intep2(f,a,b,n,type)% Metodo de NC P0 o del trapecio P1interv=a :(b-a)/(n-1) :b ;j=0 ;for ii=1 :length(interv)-1if type==’max’fb=max(f(interv(ii)),f(interv(ii+1)) ) ;elseif type==’min’fb=max(f(interv(ii)),f(interv(ii+1)) ) ;elseif type==’tra’fb=(f(interv(ii))+f(interv(ii+1)))/2 ;endj=j+fb*(interv(ii+1)-interv(ii)) ;endendNota : Se tiene que crear en un script a parte la funcion :
function j=intep2(f,a,b,n)
1
% Formula de NC de orden 2 : Simpson cerradointerv=a :(b-a)/(n-1) :b ;j=0 ;for ii=1 :length(interv)-1fb0=f(interv(ii)) ;fb1=f((interv(ii)+interv(ii+1))/2) ;fb2=f(interv(ii+1)) ;h=((interv(ii+1)-interv(ii))/2) ;j=j+(h/3)*(fb0+4*fb1+fb2) ;endendNota : Se tiene que crear en un script a parte :
clear allclose allclcformat long
disp(’Primer caso : int(x∧2,0,2)’)valex1=2∧3/3metmax1=intep0(@func1tp4,0,2,100,’max’)metmax1-valex1metmin1=intep0(@func1tp4,0,2,100,’min’)metmin1-valex1mettra1=intep0(@func1tp4,0,2,100,’tra’)mettra1-valex1metsim1=intep2(@func1tp4,0,2,100)disp(’En este caso el metodo deberia ser exacto (aslvo errores numericas)’)metsim1-valex1
metmax1p=intep0(@func1tp4,0,2,10000,’max’)metmax1p-valex1metmin1p=intep0(@func1tp4,0,2,10000,’min’)metmin1p-valex1mettra1p=intep0(@func1tp4,0,2,10000,’tra’)mettra1p-valex1metsim1p=intep2(@func1tp4,0,2,10000)disp(’Se amplian los errores’)metsim1p-valex1
disp(”)disp(’Segundo caso : int(x∧2,2,0) y int(x∧3,-2,2)’)intep0(@func1tp4,2,0,10000,’tra’)intep0(@func2tp4,-2,2,10000,’tra’)
disp(”)disp(’Tercer caso : int(exp(x),0,1)’)
2
valex2=exp(1)-1metmax2=intep0(@func3tp4,0,1,100,’max’)metmax2-valex2metmin2=intep0(@func3tp4,0,1,100,’min’)metmin2-valex2mettra2=intep0(@func3tp4,0,1,100,’tra’)mettra2-valex2metsim2=intep2(@func3tp4,0,1,100)metsim2-valex2
metmax2p=intep0(@func3tp4,0,1,10000,’max’)metmax2p-valex2metmin2p=intep0(@func3tp4,0,1,10000,’min’)metmin2p-valex2mettra2p=intep0(@func3tp4,0,1,10000,’tra’)mettra2p-valex2metsim2p=intep2(@func3tp4,0,1,10000)metsim2p-valex2
1.2 Integracion en 2d : Formulas de NC de orden 0, 1
Nota : Se tiene que crear en un script a parte la funcion :
function j=func4tp4(x,y)j=x∧2+y∧2 ;end
Nota : Se tiene que crear en un script a parte la funcion :
function j=intep0d2(f,a,b,n,c,d,m,type)% Metodo de NC P0 o del prismo en dim 2intervx=a :(b-a)/(n-1) :b ;intervy=c :(b-a)/(m-1) :d ;j=0 ;for ii=1 :length(intervx)-1for jj=1 :length(intervy)-1xa=intervx(ii) ;xb=intervx(ii+1) ;ya=intervy(ii) ;yb=intervy(ii+1) ;if type==’max’fb=max([f(xa,ya),f(xa,yb),f(xb,ya),f(xb,yb)]) ;elseif type==’min’fb=min([f(xa,ya),f(xa,yb),f(xb,ya),f(xb,yb)]) ;elseif type==’tra’fb=(f(xa,ya)+f(xa,yb)+f(xb,ya)+f(xb,yb))/4 ;end
3
j=j+fb*(xb-xa)*(yb-ya) ;endendNota : Se tiene que crear en un script :
clear allclose allclcformat longdisp(”)disp(’int(x∧2+y∧2,0,2)’)valex3=2/3metmax3=intep0d2(@func4tp4,0,1,100,0,1,100,’max’)metmax3-valex3metmin3=intep0d2(@func4tp4,0,1,100,0,1,100,’min’)metmax3-valex3mettra3=intep0d2(@func4tp4,0,1,100,0,1,100,’tra’)mettra3-valex3metmax3p=intep0d2(@func4tp4,0,1,500,0,1,500,’max’)metmax3p-valex3metmin3p=intep0d2(@func4tp4,0,1,500,0,1,500,’min’)metmax3p-valex3mettra3p=intep0d2(@func4tp4,0,1,500,0,1,500,’tra’)mettra3p-valex3
2 Ejercicios
a) Crear un script que permite aproximar la integral de una funcion en dimension 1 (esdecir, del estilo :
∫
b
af(x) dx) mediante una formula de Newton-Cotes de orden 3 (teneis
que utilizar el resultado encontrado en el ejercicio b) del TP4 de MAPLE).
b) Aproximar∫
1
0 exp(x) dx utilizando el algoritmo desarrollado en a).
4
TP 5 MAPLE - Sistemas de ecuaciones
MASTER T.E.C.I.
1 Comandos MAPLE
1.1 Sistemas lineales
with(LinearAlgebra) ;A := Matrix([[1, 2, 3], [0, 3, 4], [1, 0, 5]]) ;Determinant(A) ;b := Vector([1, 2, 3]) ;1/A.b ;LinearSolve(A, b) ;LinearSolve(A, b, method = ’LU’) ;
A := Matrix([[1, 2, 3], [3, 4, 5]]) ;b := Vector([1, 1]) ;LinearSolve(A, b, free = ’s’) ;LeastSquares(A, b, free = ’s’) ;
A := Matrix([[1, 2, 3], [3, 4, 5], [0, 2, 3], [0, 2, 3]]) ;b := Vector([1, 2, 1, 1]) ;LinearSolve(A, b, free = ’s’) ;x := LeastSquares(A, b) ;A.x ;
A := Matrix([[1, 2, 3], [3, 4, 5], [0, 2, 3], [5, 2, 3]]) ;b := Vector([1, 2, 1, 3]) ;x := LeastSquares(A, b) ;evalf(A.x-b) ;
1.2 Sistemas no lineales
restart ;f := x∧2+x-6 ;plot(f, x = 1 .. 3) ;with(Student[NumericalAnalysis]) ;
Bisection(f, x = [1, 3], tolerance = 10∧(-5)) ;
1
Bisection(f, x = [1, 3], tolerance = 10∧(-5), output = animation) ;
Newton(f, x = 1, tolerance = 10∧(-5)) ;Newton(f, x = 1, tolerance = 10∧(-5), output = animation) ;
Secant(f, x = [1, 3], tolerance = 10∧(-5)) ;Secant(f, x = [1, 3], tolerance = 10∧(-5), output = animation) ;
1.3 Un poco de optimizacion
with(Optimization) ;f := proc (x) if x < 0 then x∧2 else sin(x) end if end proc ;NLPSolve(f, -Pi .. Pi) ;
2
TP 5 MATLAB - Sistemas de ecuaciones
MASTER T.E.C.I.
1 Sistemas lineales
Nota : Se tiene que crear en un script a parte :
clear all ;close all ;clc
A=[1,2,3 ;0,1,6 ;4,2,0]b=[1 ;5 ;7]det(A)u=A∧(-1)*bA*u-blinsolve(A,b)
A=[1,2,3 ;0,1,6]b=[1 ;5]u=linsolve(A,b)A*u-b
A=[1,2,3 ;0,1,6 ;1,2,0 ;1,0,1]b=[1 ;1 ;1 ;1]u=linsolve(A,b)A*u
2 Sistemas no lineales
Nota : Se tiene que crear en un script a parte la funcion :
function F = fun1p5(x)F = x(1) - exp(-x(1)) ;endNota : Se tiene que crear en un script a parte la funcion :
function F = fun2p5(x)F = [2*x(1) - x(2) - exp(-x(1)) ;-x(1) + 2*x(2) - exp(-x(2))] ; end
1
Nota : Se tiene que crear en un script a parte :
clear allclose allclcx=0 :.1 :1 ;for i=1 :length(x)y(i)=fun1p5(x(i)) ;end
figure(1)clfhold onplot(x,y)
[xsol,fval,exitflag,output] = fzero(@fun1p5,-1)[xsol,fval,exitflag,output] = fsolve(@fun1p5,-1)plot(xsol,fval,’ok’,’markersize’,10,’linewidth’,10)
x=-1 :.1 :1 ;y=-1 :.1 :1 ;for i=1 :length(x)for j=1 :length(x)t=[x(i),y(j)] ;J=fun2p5(t) ;z1(i,j)=J(1) ;z2(i,j)=J(2) ;endend[yy,xx]=meshgrid(x,y) ;
figure(2)clfhold onsurface(xx,yy,z1)
figure(3)clfhold onsurface(xx,yy,z2)
[xsol,fval,exitflag,output] = fsolve(@fun2p5,[1,1])
figure(2)plot3(xsol(1),xsol(2),fval,’ok’,’markersize’,10,’linewidth’,10)figure(3)plot3(xsol(1),xsol(2),fval,’ok’,’markersize’,10,’linewidth’,10)
2