Está en la página 1de 12

Facultad de Ingeniería

Departamento de Ingeniería de Sistemas e Industrial

Métodos Numéricos

Docente:
Oswaldo Rojas Camacho

Códigos MATLAB®

Oscar Andrés Mancera Garzón


1. Falsa Posición
f=input('Ingrese la función: ');
x0=input('Ingrese el valor inicial x0: ');
x1=input('Ingrese el valor inicial x1: ');
iteraciones=input('Ingrese el numero de iteraciones: ');
v=1:iteraciones;
v(1)=x0;
v(2)=x1;
syms x;
index=1;
f0=subs(f,x,v(1));
f1=subs(f,x,v(index+1));
while index <= iteraciones
v(index+2)= x0 - (((x0 -v(index+1))/(f0-f1))*f0);
fprintf('x%d = %d\n',index+1,v(index+2));
index= index+1;
f1=subs(f,x,v(index+1));
end

2. Secante
f=input('Ingrese la función: ');
x0=input('Ingrese el valor inicial x0: ');
x1=input('Ingrese el valor inicial x1: ');
iteraciones=input('Ingrese el numero de iteraciones: ');
v=1:iteraciones;
v(1)=x0;
v(2)=x1;
syms x;
index=1;
fka=subs(f,x,v(index));
fk=subs(f,x,v(index+1));
while index <= iteraciones
v(index+2)= v(index+1) - (((v(index+1) -v(index))/(fk-fka))*fk);
fprintf('x%d = %d\n',index+1,v(index+2));
index= index+1;
fka=subs(f,x,v(index));
fk=subs(f,x,v(index+1));
end

3. Tangente
f=input('Ingrese la función: ');
x0=input('Ingrese el valor inicial: ');
iteraciones=input('Ingrese el numero de iteraciones: ');
v=1:iteraciones;
v(1)= x0;
syms x;
index=1;
f1=subs(f,x,v(index));
z=diff(f);
d=subs(z,x,v(index));
while(index<=iteraciones)
v(index+1)=v(index)-(f1/d);
fprintf('x%d = %d\n',index-1,v(index));
index=index+1;
f1=subs(f,x,v(index));
d=subs(z,x,v(index));
end

4. Punto Fijo
clc, clear all, close all
syms x;
f=input('Ingrese la función F(x): ');
g=input('Ingrese la función G(x) tal que G(x)=x: ');
x0=input('Ingrese el valor inicial x0: ');
iteraciones=input('Ingrese el numero de iteraciones: ');
v=1:iteraciones;
v(1)=x0;
index=1;
gi=subs(g,x,v(index));
while index <= iteraciones
v(index+1)= gi;
fprintf('x%d = %d\n',index,v(index+1));
gi=subs(g,x,v(index+1));
index=index+1;
end
%Grafica de la funcion
figure(1)
ezplot(f);grid on
hold on;
ezplot(g);grid on

5. Bisección
clc, clear all, close all
format short;
a=input('Ingrese el valor del extremo izquierdo del intervalo [a,b].
a=');
b=input('Ingrese el valor del extremo derecho del intervalo [a,b]. b=');
n=input('Ingrese el numero de iteraciones: ');
fun=input('Ingrese la función: f(x)=','s');
f=inline(fun);
ezplot(f);grid
for k=1:n
c=(a+b)/2;
e=abs((b-a)/2);
A(k,:)=[k a b c f(c) e];
if f(a)*f(c)<0
b=c;
else a=c;
end
end
fprintf('\n \tk \ta \tb \tc \tf(c) \terror \n')
disp(A)
fprintf('Solución: \n c-%8.5f\n',c)
fprintf('f(c)=%8.5f\n\',f(c))
fprintf('error=%8.5f\n',e)
figure(2);plot(A(:,4));title('Solucion');grid
figure(3);plot(A(:,6));title('Error');grid

6. Falsa Posición 2
%Tecnica de la Falsa Posicion
clc, clear all, close all
format short;
%format long;
disp('Tecnica de la Falsa Posicion')
a=input('Ingrese a : ');
c=input('Ingrese c : ');
e=input('Ingrese el error : ');
Fx=input('Ingrese la funcion: ','s');
x=a;
Fa=eval(Fx);
x=c;
Fc=eval(Fx);
fprintf('\n %6a %7s %8s %10s %8s %8s %8s \n ',
'A','B','C','F(a)','F(b)','F(c)','|c-a|');
while abs(c-a)/2>e
b=(c*Fa-a*Fc)/(Fa-Fc);
x=b;
Fb=eval(Fx);
fprintf('\n %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f
\n',a,b,c,Fa,Fb,Fc,abs(c-a)/2);
if abs(Fc)<e
break;
else
if Fa*Fb<=0
c=b;
Fc=Fb;
else
a=b;
Fa=Fb;
end
end
end
%fprintf('\nLa Solucion %.4f,b);
fprintf('Solucion: \n b=%8.5f\n',b)
fprintf('Fb=%8.5f\n',Fb)
ezplot(Fx);%grafica de la funcion
grid on;

7. Newton-Raphson
f=input('Ingrese la función: ');
x0=input('Ingrese el valor inicial: ');
iteraciones=input('Ingrese el numero de iteraciones: ');
v=1:iteraciones;
v(1)= x0;
syms x;
%Grafica de la funcion
ezplot(f);grid on
index=1;
f1=subs(f,x,v(index));
z=diff(f);
d=subs(z,x,v(index));
while(index<=iteraciones)
v(index+1)=v(index)-(f1/d);
fprintf('x%d = %d\n',index-1,v(index));
index=index+1;
f1=subs(f,x,v(index));
d=subs(z,x,v(index));
end

8. Newton-Raphson 2
clc, clear all, close all
format short;
%format long;
disp('Metodo de Newton Raphson')
syms x
f=input('Introduzca la funcion: f(x)= ');
x0=input('Introduzca el punto de inicio: x0= ');
error =input('Introduzca el error: error = ');
%Grafica de la funcion
ezplot(f);grid on
%Derivada de la funcion
d=diff(f);
d=inline(d);
f=inline(f);
ea=100;
j=0;
while ea>error
xi=x0-(x0/d(x0));
ea=abs(((xi-x0)/xi)*100);
x0=xi;
j=j+1;
fprintf('\nRaiz=%.5f en %d Iteraciones\n',x0,j)
end
fprintf('\nRaiz=%.5f en %d Iteraciones\n',x0,j)

9. Secante Modificado
%Tenica numerica de la secante
clc, clear all
disp('Metodo de la secante')
format short;
%format long;
xf(1)=input('Ingrese el primer valor de x1: x1= ');
xf(2)=input('Ingrese el segundo valor de x2: x2= ');
tol=input('Ingrese la cota de tolerancia: tol= ');
syms x;
f=input('Ingrese la funcion: ');
f1=subs(f,x,xf(1));
f2=subs(f,x,xf(2));
ea(1)=100;
i=1;
j=2;
figure(1)
ezplot(f);grid
while abs(ea(1))>=tol
xf(j+1)=(xf(j-1)*f2-xf(j)*f1)/(f2-f1);
f1=f2;
f2=subs(f,x,xf(j+1));
ea(i+1)=(xf(j+1)-xf(j))/xf(j+1)*100;
j=j+1;
i=i+1;
end
figure(2)
plot(xf,'r');title('Solucion');grid
figure(3);plot(ea,'b');title('error');grid
fprinf(' i xf(1) Error aprox (i) \n');
for k=2:j;
fprintf('%2d\t%11.7f\t%7.3f\n',k-1,xf(k),ea(k-1));
end

10. Interpolacion
%Interpolacion
%xdat = [1 5 10 30 50];
xdat = input('x = ')
%ydat = log(xdat);
ydat = input('y = ')
plot(xdat,ydat,'or')
hold on;
pause;
p = polyfit(xdat,ydat,1); % grado 1
xvet=1:0.1:50;
plot(xvet,polyval(p,xvet),'-');
hold on;
grid;
pause;
p = polyfit(xdat,ydat,2) % grado 2;
plot(xvet,polyval(p,xvet));
hold on;
grid;
pause;
p = polyfit(xdat,ydat,3) % grado 3;
plot(xvet,polyval(p,xvet));
hold on;
grid;
pause;
p = polyfit(xdat,ydat,4) % grado 4;
plot(xvet,polyval(p,xvet));

11. Interpolación No Lineal


clc, clear all, close all
x1= 0.5;
x2= 2.2;
X =[x1;x2];

f1 = @(x1,x2) x1^2 - x2^2 + 2*x2;


f2 = @(x1, x2) 2*x1 +x2^2 -6;

a11 = @(x1) 2*x1;


a12 = @(x2) -2*x2 + 2;
a21 = 2;
a22 = @(x2) 2*x2;

for i = 1 : 10
J = [a11(X(1)) a12(X(2)); a21 a22(X(2))];
F = [f1(X(1), X(2)); f2(X(1), X(2))];
x = X - inv(J)*F;
X = x;
end

f1(X(1), X(2))
f2(X(1), X(2))
X

12. Newton Raphson No Lineal


clc, clear all, close all
disp('Methodo de Newthon-Raphson - 2 variables')
syms x y;

%funciones de prueba
%f1nameFun = (x^2)-(2*x)- y + 0.5;
%f2nameFun = (x^2)+(4*y^2) - 4;

f1name = input('F1(x,y) = ');


f2name = input('F2(x,y) = ');
gradf1 = [diff(f1name,'x') diff(f1name,'y')];
gradf2 = [diff(f2name,'x') diff(f2name,'y')];
disp('');
w = input('Valores Iniciales [Xo Yo] = ');
v = w';
tol = input('Tolerancia: ');
nitermax = input('Numero de iteracciones k = ');
%Grafica de la funcion
figure(1)
ezplot(f1name);grid on
hold on;
ezplot(f2name);grid on
fprintf('F1(x,y) = %s \n',f1name);
fprintf('F2(x,y) = %s \n',f2name);

disp(sprintf('Los valores iniciales son xo = %- 4.2f y yo = %-


4.2f',v(1),v(2)))
disp(sprintf('El numero maximo de iteracciones k = %3.0f\n con tolerancia
de: %4.2e', nitermax,tol))
disp('')
disp(' k x(k) y(k) F1(x(k),y(k))
F2(x(k),y(k))')
disp('-------------------------------------------------------------------
----------------------')
x = v(1);
y = v(2);
fv1 = eval(f1name);
fv2 = eval(f2name);
fxo = [fv1;fv2];
f1pv = eval(gradf1);
f2pv = eval(gradf2);
%Nace el Jacobiano
fpxo =[f1pv;f2pv];
if det(fpxo)==0
disp('Error: determinante del Jacobiano es 0, intente otro valor
inicial')
else
iter = 0;
s1 = sprintf('%3.0f %- 10.4f %- 10.4f',iter,v(1),v(2));
s2 = sprintf(' %- 14.4f %- 14.4f',fv1,fv2);
disp([s1 s2])
while (norm(fxo)>tol) & (det(fpxo)~=0) & (iter<nitermax)
iter = iter + 1;
vn = v - inv(fpxo)*fxo;
v = vn;
x = v(1);
y = v(2);
fv1 = eval(f1name);
fv2 = eval(f2name);
fxo = [fv1;fv2];
f1pv = eval(gradf1);
f2pv = eval(gradf2);
fpxo =[f1pv;f2pv];
if det(fpxo)==0
disp('Error: determinante del Jacobiano es 0, intente otro valor
inicial')
end
s1 = sprintf('%3.0f %- 10.4f %- 10.4f',iter,v(1),v(2));
s2 = sprintf(' %- 14.4f %- 14.4f',fv1,fv2);
disp([s1 s2])
end
root = v;
disp(sprintf('\n Las raices son: x = %- 8.4f, y = %- 8.4f',v(1),v(2)))
end

13. Lagrange
%POLINOMIO DE LAGRAGE"
clc,clear
fprintf('INTERPOLACION "POLINIMIO DE LAGRAGE"\n');
xi=input('Ingrese los puntos de x[]: ');
yi=input('Ingrese los puntos de y[]: ');
n=length(xi);
x=sym('x');
for j=1:n
producto=1;
for i=1:j-1
producto=producto*(x-xi(i));
end
producto2=1;
for i=j+1:n
producto2=producto2*(x-xi(i));
end
producto3=1;
for i=1:j-1
producto3=producto3*(xi(j)-xi(i));
end
producto4=1;
for i=j+1:n
producto4=producto4*(xi(j)-xi(i));
end
L(j)=(producto*producto2)/(producto3*producto4);
fprintf('\n L%d:\n',j-1)
disp(L(j))
end

pn=0;
for j=1:n
pn=pn+L(j)*yi(j);
end
fprintf('Polinomio: \n')
disp(pn)
figure(1)
ezplot(pn);grid on
figure(2)
sn = simplify(pn)
disp(sn)
ezplot(sn);grid on

14. Regresión lineal


clc, clear all, close all
%Regresion Lineal
disp('.:Regresion Lineal - Prueba 2:.')

%Puntos
x=[0,1,3,4.5,5,9];
y=[1.5,3,4,4.1,7,9];
%coef _ ajust
p=ajuste(x,y,2);

%Grafica
hold on
plot(x,y,'kp','markersize',7,'markerfacecolor','b')%modi
z=@(x) polyval(p,x);
fplot(z,[x(1),x(end)])
xlabel('x')
ylabel('y')
grid on
hold off

function p = ajuste(x, y, n)
%Matriz de Vandermonte:
x = x(:);
V = ones(length(x), n + 1);
for j = n:-1:1
V(:, j) = V(:, j + 1) .* x;
end
% Soluciona cuadrados:
[Q, R] = qr(V, 0);
p = transpose(R \ (transpose(Q) * y(:)));
end

15. Regresión Exponencial


clc, clear all, close all
%Regresion Lineal
disp('.:Regresion Lineal - Prueba 2:.')

%Puntos
x=[1 2 8 10 23 42];
y=[7 15 10 25 29 50];
%ajuste
p=ajuste(x,log(y),1);
fprintf('Exp a= %2.3f\n',p(1));
fprintf('Co-eficiente c = %3.3f\n',exp(p(2)));

%Graf
hold on
plot(x,y,'kp','markersize',6,'markerfacecolor','k')
%rev
z=@(x) exp(p(2))*exp(x*p(1));
fplot(z,[x(1),x(end)])
xlabel('x')
ylabel('y')
grid on
title('Reg Exponencial')

function p = ajuste(x, y, n)
%Matriz de Vandermonte:
x = x(:);
V = ones(length(x), n + 1);
for j = n:-1:1
V(:, j) = V(:, j + 1) .* x;
end
% Soluciona cuadrados:
[Q, R] = qr(V, 0);
p = transpose(R \ (transpose(Q) * y(:)));
end

16. Spline Cubico


clc,clear
fprintf('TEST SPLINE .:PEND REVISAR:. "\n');
n=input('Numero de puntos: ');
%x(1)=-1;
%y(1)=1/(1+25*x(1)^2);
%x(n)=1;
%y(n)=1/(1+25*x(n)^2);
%dx=(x(n)-x(1))/(n-1);
%for i=2:n-1
% x(i)=x(i-1)+dx;
% y(i)=1/(1+25*x(i)^2);
%end
for i=1:n
x(i)=input('Introduzca el valor de X: ');
y(i)=input('Introduzca el valor de Y: ');
end
[a,b,c,d]=genspline(x,y,n);
%plot spline
dx=(x(n)-x(1))/100;
for i=1:101
xx(i)=x(1)+(i-1)*dx;
yy(i)=evalspline(a,b,c,d,xx(i),x,n);
%ytrue(i)=1/(1+25*xx(i)^2);
end
%plot(xx,yy,xx,ytrue,'+')
plot(xx,yy)
xlabel('x')
ylabel('y')

function [a,b,c,d]=genspline(x,y,n)
%genera coefficientes de un spline cubico
%computa el largo del intervalo y lo guarda en h
for i=1:n-1
h(i)=x(i+1)-x(i);
end
%computa la matriz A
A(1,1)=1;
A(n,n)=1;
f=zeros(n,1);
for i=2:n-1
A(i,i)=2*(h(i)+h(i-1));
f(i)=6*((y(i+1)-y(i)-y(i-1))/h(i-1));
end
for i=2:n-2
A(i,i+1)=h(i+1);
end
for i=3:n-1
A(i,i-1)-h(i);
end
%resuelve para vector s
s=A\f;
%computa coeficientes
for i=2:n-1
a(i)=(s(i+1)-s(i))/(6*h(i));
b(i)=s(i)/2;
c(i)=(y(i+1)-y(i))/h(i)-(2*h(i)*s(i)+h(i)*s(i+1))/6;
d(i)=y(i);
end
end
function yy=evalspline(a,b,c,d,xx,x,n)
%evalua el spline en xx
%determina cusl interval xx esta
i=1;
while (xx > x(i+1) & i <= n-1)
i=i+1;
end
%xx esta entre x(i) y x(i+1)
yy=a(i)*(xx-x(i))^3+b(i)*(xx-x(i))^2+c(i)*(xx-x(i))+d(i);
end
function plotspline(a,b,c,d,x,n)
%plot 100pts
dx=(x(n)-x(i))/100;
for j=1:101
xx(j)=x(1)+dx*(j-1);
yy(j)=evalspine(a,b,c,d,xx(j),x,n);
end
pol = polyfit(xx,yy,n);
fprintf('Polinomio: \n')
disp(pol)
plot(xx,yy);
end

También podría gustarte