Está en la página 1de 22

Programas Matlab para el curso de Métodos

Numéricos
Karina Malla Buchhorsts

Académica del Departamento de Enseñanza de las Ciencias Básicas

Enero, 2018

Índice

1. Ecuaciones No Lineales 2
1.1. Método de Newton . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2. Método del punto jo . . . . . . . . . . . . . . . . . . . . . . 3

2. Sistemas de Ecuaciones Lineales 5


2.1. Métodos Iterativos: Gauss-Seidel . . . . . . . . . . . . . . . . 5

3. Interpolación 8
3.1. Interpolación de Lagrange/Spline . . . . . . . . . . . . . . . . 8
3.2. Interpolación de Newton . . . . . . . . . . . . . . . . . . . . . 12

4. Diferenciación Numérica 15
4.1. Método en diferencias de 2 puntos . . . . . . . . . . . . . . . 15

5. Integración Numérica 16
5.1. Método del Trapecio . . . . . . . . . . . . . . . . . . . . . . . 16
5.2. Método de Simpson . . . . . . . . . . . . . . . . . . . . . . . . 17

6. Solución de Ecuaciones Diferenciales ordinarias 18


6.1. Métodos de un paso . . . . . . . . . . . . . . . . . . . . . . . 18
6.1.1. Runge-Kutta . . . . . . . . . . . . . . . . . . . . . . . 18
6.2. Métodos multipaso . . . . . . . . . . . . . . . . . . . . . . . . 19
6.2.1. ABM . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

1
1. Ecuaciones No Lineales

1.1. Método de Newton


1 function [x,iter]=newton(x0)
2
3 % newton-raphson algorithm
4
5 N = 100; eps = 1.e-5; % define max. no. iterations and error
6
7 maxval = 10000.0; % define value for divergence
8
9 xx = x0;
10
11 % definir la funcion f y su derivada
12
13 f = inline('exp(-x).*log(x)','x'); % define la funcion f
14
15 fp = inline('exp(-x).*(1./x-log(x))','x'); % define la derivada de f
16
17
18
19 % muestra los valores en la linea de comandos
20
21 disp(['n', ' xn ', ' xn+1 ', ' error']);
22
23
24
25 % graficar para tener una idea de las raices
26
27 x = [0.9:0.01:1.01]';y=f(x);
28
29 plot(x,y);xlabel('x');ylabel('f(x)');
30
31 grid on
32
33
34
35 while (N>0)
36
37 xn = xx-f(xx)/fp(xx);
38
39 if abs(f(xn))<eps
40

2
41 x=xn;iter=100-N;
42
43 return
44
45 end
46
47 disp([num2str(101-N),' ',num2str(xx),' ',num2str(xn),'
',num2str(abs(xn-xx))]);
48
49 if abs(f(xx))>maxval
50
51 disp(['iterations = ',num2str(iter)]);
52
53 error('Solution diverges');
54
55 break
56
57 end
58
59 N = N - 1;
60
61 xx = xn;
62
63 end
64
65 error('No convergence');
66
67 return
68
69 % end function

1.2. Método del punto jo


1 function y = fixedpoint
2
3 g = inline('1+x-(x^2)/3','x');
4
5 p0= -1;
6
7 tol= 10^-10;
8
9 max1 = 1000;
10

3
11 epsi=10^-12;
12
13 Nuit=1000;
14
15 a=-2; b=0;
16
17 disp(['n', ' xn ', ' g(xn) ', ' error']);
18
19 for k=1:max1
20
21 p = g(p0); %p = feval(g,p0);
22
23 abserr = abs(p-p0);
24
25 relerr = abserr/( abs(p)+eps );
26
27 % eps is a MATLAB defined constant for machine epsilon, to avoid
28
29 % division by 0
30
31 if (abserr<tol)&(relerr<tol)
32
33 break % jump out of the loop; were done
34
35 end
36
37 disp([num2str(k),' ',num2str(p0),' ',num2str(p),'
',num2str(abserr)]);
38
39 p0 = p;
40
41 end
42
43 if (k==max1)
44
45 disp('The algorithm did not converge')
46
47 end
48
49 y = p;

4
2. Sistemas de Ecuaciones Lineales

2.1. Métodos Iterativos: Gauss-Seidel


1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
3 % This code finds the solution to a system of simultaneous linear
equation
4
5 % using Gauss_Seidel Method.
6
7 % Written By: Mohammad Y. Saadeh, on 06/14/2010, University of
Nevada Las
8
9 % Vegas
10
11 % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %A % % % % % % % % % % % % % % % % % % % % % % % % %
12
13
14
15 clear;clc
16
17 format compact
18
19 % % Read or Input any square Matrix
20
21 % A = [-6 2 1 2 1;
22
23 % 3 8 -4 1 0;
24
25 % -1 1 4 10 1;
26
27 % 3 -4 1 9 2;
28
29 % 2 0 1 3 10]; % coefficients matrix
30
31 % C = [3;4;-2 ;12;1]; % constants vector
32
33 % % Sistema Ax=b, Burden: Ejemplo 3, Cap 7
34
35 % A = [4 -1 1;
36
37 % -1 -2 1;
38

5
39 % 2 1 -4]; % coefficients matrix
40
41 % C = [-14; 5; -19]; % constants vector
42
43 A = [-2 1 0 0;
44
45 1 -2 1 0;
46
47 0 1 -2 1;
48
49 0 0 1 -2]; % coefficients matrix
50
51 C = [1; 1; 1; 1]; % constants vector
52
53 epsilon = 0.001; % tolerancia
54
55 N = 100; % numero mximo de iteraciones
56
57 n = length(C);
58
59 X = zeros(n,1);
60
61 Error_eval = 1;
62
63
64
65 % % Check if the matrix A is diagonally dominant
66
67 for i = 1:n
68
69 j = 1:n;
70
71 j(i) = [];
72
73 B = abs(A(i,j));
74
75 Check(i) = abs(A(i,i)) - sum(B); % Is the diagonal value
greater than the remaining row values combined?
76
77 if Check(i) < 0
78
79 fprintf('The matrix is not strictly diagonally dominant at
row %2i\n\n',i)
80
81 end

6
82
83 end
84
85
86
87 % % Start the Iterative method
88
89
90
91 iteration = 0;
92
93 while (Error_eval > epsilon & iteration < N)
94
95 iteration = iteration + 1;
96
97 Z = X; % save current values to calculate error later
98
99 for i = 1:n
100
101 j = 1:n; % define an array of the coefficients' elements
102
103 j(i) = []; % eliminate the unknow's coefficient from the
remaining coefficients
104
105 Xtemp = X; % copy the unknows to a new variable
106
107 Xtemp(i) = []; % eliminate the unknown under question from
the set of values
108
109 X(i) = (C(i) - sum(A(i,j) * Xtemp)) / A(i,i);
110
111 end
112
113 Xsolution(:,iteration) = X;
114
115 %Error_eval = max(sqrt((X - Z).^2));
116
117 Error_eval = max(abs(X - Z))/max(abs(X));
118
119 %Error_eval = max(abs(X - Z));
120
121 Xerror(:,iteration) = Error_eval;
122
123 end
124

7
125
126
127 % % Display Results
128
129 disp('Nmero Iteracin / Solucin / Error')
130
131 GaussSeidelTable = [1:iteration;Xsolution;Xerror]
132
133 %MaTrIxSystem = [A X C]

3. Interpolación

3.1. Interpolación de Lagrange/Spline


1 function interp_lagrange_spline
2
3
4
5 % Nov/2017
6
7 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
8
9 % INTERPOLACION SPLINE CUBICO
10
11 % Efecta la interpolacin de la nube de puntos dada por los vectores
x,y
12
13 % por medio de splines cbicos.
14
15 % En la salida (variable yy) obtenemos los valores del spline
evaluado en los puntos dados en el vector xx.
16
17 %
18
19 % En su sintaxis "reducida" pp = spline(x,y) devuelve la forma
polinomial a trozos del spline cbico
20
21 % interpolador de la nube x, y. Para evaluarlo, hay que aplicarle
la funcin ppval, equivalente a polyval
22
23 % para polinomios. As,
24

8
25 % pp = spline(x,y);
26
27 % yy=ppval(pp,xx);
28
29 % esta forma nos permite hallar explcitamente los coeficientes del
spline construido, en caso de que
30
31 % los necesitemos. La funcin que se encarga de "trocear" el spline
y sacar esta informacin se llama unmkpp
32
33 % (de ``unmake piecewise polynomial''). Su sintaxis es
34
35 % [nodos,coefs,nro de trozos, orden, dim] = unmkpp(pp)
36
37 % donde el orden = grado + 1, y dim se refiere a si el spline es
uni o multivariante.
38
39 %
40
41 % Si el spline cubico es Sujeto, entonces definimos un vector y1
como:
42
43 % y1 = [y0 y yn];
44
45 % este vector contiene dos valores ms que el vector x, en este
caso, y0 e yn se usan como valores de la
46
47 % derivada en los nodos extremos, en este caso, escribimos:
48
49 % pp=spline(x,y1);
50
51 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
52
53
54
55
56
57 % Ejemplo. Tabla de datos
58
59 % Coordenadas figura pato (Burden p149)
60
61 x = [0.9 1.3 1.9 2.1 2.6 3.0 3.9 4.4 4.7 5.0 6.0 7.0 8.0 9.2 10.5
11.3 11.6 12.0 12.6 13.0 13.3];
62

9
63 y = [1.3 1.5 1.85 2.1 2.6 2.7 2.4 2.15 2.05 2.1 2.25 2.3 2.25 1.95
1.4 0.9 0.7 0.6 0.5 0.4 0.25];
64
65
66
67
68
69 % Interpolacion Spline Cubico
70
71 pp = spline(x,y);
72
73
74
75
76
77 % Puntos a interpolar
78
79 xx = 0.9:0.1:13.3;
80
81
82
83 % Evaluando estos puntos en el polinomio de interpolacion obtenido
84
85 yy=ppval(pp,xx);
86
87
88
89 % Graficando el conjunto de datos inicial (tabla de datos), y los
nodos interpolados
90
91 plot(x,y,'o',xx,yy); hold on
92
93
94
95 % Obteniendo los coeficientes del polinomio en cada tramo
96
97 [nodos,coefs,nro_tramos, orden, dim] = unmkpp(pp);
98
99
100
101 % Se muestran los resultados por pantalla
102
103 X=nodos(1:20); X=X';
104
105 fprintf('Salida spline: Xj Aj Bj Cj Dj')

10
106
107 nodos_coeficientes=[X coefs(:,4) coefs(:,3) coefs(:,2) coefs(:,1)]
108
109
110
111
112
113
114
115
116
117 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
118
119 % INTERPOLACION DE LAGRANGE
120
121 % considerando la misma tabla de datos
122
123 y0 = xx*0;
124
125 n = length(x);
126
127 m = length(xx);
128
129 for k = 1 : m
130
131 x1 = xx(k);
132
133 y1 = 0;
134
135 for j = 1 : n
136
137 t = 1;
138
139 for i = 1 : n
140
141 if i~=j
142
143 t = t * (x1-x(i))/(x(j)-x(i));
144
145 end
146
147 end
148
149 y1 = y1 + t*y(j);
150

11
151 end
152
153 y0(k)=y1;
154
155 end
156
157
158
159 % Graficamos la solucion
160
161 plot(xx, y0,'m'); grid on; legend('nodos xj','spline','lagrange')

3.2. Interpolación de Newton


1 function F = divided_diff(x,y,x0)
2
3
4
5 %divided_diff(x,y,x0) computes the divided differences table based
on the n points
6
7 %with coordinates (x,y).
8
9 %Those divided differences are needed to construct the (n-1)th
Lagrange polynomial
10
11 %using the Newton's interpolatory divided difference formula
12
13 %n is the number of points, hence the interpolatory polynomial has
degree n-1
14
15 %x0 is point for which we want an approximation of f(x0) based on
the polynomial
16
17
18
19 %This file was generated after following a course in applied
numerical methods
20
21 %at the University of Pretoria, Department of Geology, Geophysics
division.
22

12
23 %The polynomial evaluation was taken from the book of John H.
Mathews, Numerical
24
25 %Methods for Mathematics, Science and Engineering, 2nd Ed.
26
27
28
29 %Author: Alain G. Kapitho
30
31 %Date : Dec. 2005
32
33
34
35
36
37 %getting the number of points from the x-vector
38
39 n = size(x,1);
40
41 if n == 1
42
43 n = size(x,2);
44
45 end
46
47
48
49
50
51 %the 1st column in the divided differences table
52
53 for i = 1:n
54
55 F(i,1) = y(i);
56
57 end
58
59
60
61 %the rest of the entries in the table
62
63 for i = 2:n
64
65 for j = 2:i
66

13
67 F(i,j)=(F(i,j-1)-F(i-1,j-1))/(x(i)-x(i-j+1));
68
69 end
70
71 end
72
73
74
75
76
77
78
79 %evaluating the polynomial at the specified point
80
81 fx0 = F(n,n);
82
83 for i = n-1:-1:1
84
85 fx0 = fx0*(x0-x(i)) + F(i,i);
86
87 end
88
89
90
91
92
93 %visualization of the data set
94
95 plot(x,y,'b*')
96
97 hold on
98
99 plot(x,y)
100
101 hold on
102
103 plot(x0, fx0, 'r.')
104
105
106
107
108
109 %command window outputs
110
111 disp('Point x0 where approximation of f(x0) is needed')

14
112
113 x0
114
115 disp('Evaluation of the polynomial at the specified point yields')
116
117 fx0
118
119 disp('Divided-differences table')

4. Diferenciación Numérica

4.1. Método en diferencias de 2 puntos


1 function d=der2p(x,y);
2
3 %d=der2p(x,y)
4
5 %archivo .m que sirve para determinar la derivada de una funcin
dada por
6
7 %medio de puntos igualmente espaciados en x con tamao de paso h,
por medio
8
9 %de la formula de dos puntos.
10
11 %En los puntos extremos se utilizan las formulas de diferencias
finitas
12
13 %progresivas y regresivas y en los puntos medios se usa la formula
de
14
15 %diferencias finitas centradas.
16
17 %las variables x y y son vectores de igual tamao que incluyen los
valores
18
19 %de la funcin en x y en y. Estos vectores deben ser de tamao mayor o
20
21 %igual que 3
22
23 %
24

15
25
26
27 if size(x)==size(y) %se observa que los dos vectores sean del
mismotamao
28
29 [m,n]=size(x);
30
31 h=x(2)-x(1); %tamao del paso
32
33 if n>=3 %se verifica que se den mas de dos puntos
34
35 for i=2:n-1 %se trabajan con los puntos intermedios
36
37 d(i)=(y(i+1)-y(i-1))/(2*h);
38
39 end
40
41 d(1)=(y(2)-y(1))/h;
42
43 d(n)=(y(n)-y(n-1))/h;
44
45 else
46
47 d='se deben dar mas de dos puntos'
48
49 end
50
51 else
52
53 d='los vectores x y y deben ser del mismo tamao'
54
55 end

5. Integración Numérica

5.1. Método del Trapecio


1 function I = int_trap
2
3 hold off
4
5 a=1; b=2; n=10;

16
6
7 f=inline('x.*log(x)');
8
9 h=(b-a)/n;
10
11 x=a+(0:n)*h; y=f(x);
12
13 I=h/2*(y(1)+y(n+1));
14
15 if n>1 I=I+h*sum(y(2:n)); end
16
17 h2=(b-a)/10;
18
19 xc=a+(0:100)*h2;fc=f(xc);
20
21 plot(xc,fc,'r');hold on
22
23 title('Regla de los Trapecios');
24
25 xlabel('x');ylabel('y');
26
27 plot(x,y);
28
29 plot(x,zeros(size(x)))
30
31 for i=1:n;plot([x(i),x(i)],[0,y(i)]);end

5.2. Método de Simpson


1 function I= int_simpson
2
3 hold off
4
5 a=0; b=pi; n=100;
6
7 f=inline('sin(x)');
8
9 h=(b-a)/n;
10
11 x=a+(0:n)*h; y=f(x);
12
13 I=(h/3)*(y(1)+ 4*sum(y(2:2:n)) +y(n-1));
14

17
15 if n>2 I=I+(h/3)*2*sum(y(3:2:n)); end
16
17 h2=(b-a)/100;
18
19 xc=a+(0:100)*h2;fc=f(xc);
20
21 plot(xc,fc,'r');
22
23 hold on
24
25 title('Regla de Simpson');
26
27 xlabel('x');ylabel('y');
28
29 for i=1:2:n
30
31 p=polyfit([x(i),x(i+1),x(i+2)],[y(i),y(i+1),y(i+2)],2);
32
33 hp=(x(i+2)-x(i))/10;
34
35 xp=x(i)+(0:10)*hp;
36
37 fp=polyval(p,xp);
38
39 plot(xp,fp);
40
41 end
42
43 plot(x,zeros(size(x)))
44
45 for i=1:2:n+1;plot([x(i),x(i)],[0,y(i)]);end
46
47 for i=2:2:n;plot([x(i),x(i)],[0,y(i)],'--');end
48
49 %grid on;

6. Solución de Ecuaciones Diferenciales ordinarias

6.1. Métodos de un paso


6.1.1. Runge-Kutta

1 % PROGRAMA DE RUNGE-KUTTA CALCULA LOS PARAMETROS K1 K2 K3 K4

18
2
3 %clear all,clf,clc
4
5 Eq=inline('cos(2*t)+sin(3*t)','t','y');
6
7 y=1;H=0.1; % tamao de paso
8
9 ynew=1;
10
11 disp(' RESULTADOS FINALES ')
12
13 disp(' t y k1 k2 k3 k4 ')
14
15 for t=0:H:1
16
17 fprintf('\n %7.2f %7.8f',t,y)
18
19 k1=H*Eq(t,y);
20
21 k2=H*Eq(t+H/2,y+k1/2);
22
23 k3=H*Eq(t+H/2,y+k2/2);
24
25 k4=H*Eq(t+H,y+k3);
26
27 y=y + (k1+2*(k2+k3)+k4)/6;
28
29 fprintf(' %8.8f %8.8f %8.8f %8.8f\n',k1,k2,k3,k4)
30
31 if (t<1)
32
33 ynew=[ynew y];
34
35 end
36
37 end
38
39 t=0:H:1;
40 plot(t,ynew,'-d')

6.2. Métodos multipaso


6.2.1. ABM

19
1 function [t,y]=abm4;
2
3 % OBS. Para ejecutar el programa, escribir en la linea de comandos
4
5 % >> [t,y]=abm4;
6
7 % Adams-Bashforth-Moulton 4-th order predictor-corrector method for
initial value problems
8
9 % It uses
10
11 % Adams-Bashforth 4-step method as a precdictor,
12
13 % Adams-Moulton 3-step method as a corrector, and
14
15 % Runge-Kutta method of order 4 as a starter
16
17 %
18
19 % Input:
20
21 % f - Matlab inline function f(t,y)
22
23 % a,b - interval
24
25 % ya - initial condition
26
27 % n - number of subintervals (panels)
28
29 %
30
31 % Output:
32
33 % y - computed solution
34
35 % t - time steps
36
37 %
38
39 % Example:
40
41 % y=abm4(inline('sin(y*t)','t','y'),0,1,1,10);
42
43

20
44
45 % EDO: definicion de la funcion f(t,y)
46
47 f=inline('cos(2*t)+sin(3*t)','t','y');
48
49 a=0; b=1;
50
51 ya=1;
52
53 n=10;
54
55 %
56
57 h = (b - a) / n;
58
59 h24 = h / 24;
60
61
62
63 y(1,:) = ya;
64
65 t(1) = a;
66
67
68
69 m = min(3,n);
70
71 disp(' t y ')
72
73 for i = 1 : m % start-up phase, using Runge-Kutta of order 4
74
75 fprintf('\n %7.2f %7.5f',t(i),y(i))
76
77 t(i+1) = t(i) + h;
78
79 s(i,:) = f(t(i), y(i,:));
80
81 s2 = f(t(i) + h / 2, y(i,:) + s(i,:) * h /2);
82
83 s3 = f(t(i) + h / 2, y(i,:) + s2 * h /2);
84
85 s4 = f(t(i+1), y(i,:) + s3 * h);
86
87 y(i+1,:) = y(i,:) + (s(i,:) + s2+s2 + s3+s3 + s4) * h / 6;
88

21
89 end;
90
91
92
93 for i = m + 1 : n % main phase
94
95 fprintf('\n %7.2f %7.5f',t(i),y(i))
96
97 s(i,:) = f(t(i), y(i,:));
98
99 y(i+1,:) = y(i,:) + (55 * s(i,:) - 59 * s(i-1,:) + 37 *
s(i-2,:) - 9 * s(i-3,:)) * h24; % predictor
100
101 t(i+1) = t(i) + h;
102
103 y(i+1,:) = y(i,:) + (9 * f(t(i+1), y(i+1,:)) + 19 * s(i,:) - 5
* s(i-1,:) + s(i-2,:)) * h24; % corrector
104
105 end;
106
107
108
109 t=t';
110
111
112
113 plot(t,y,'-ro')

22

También podría gustarte