Monday, May 27, 2013

Simpson composite integration algorithm in Matlab

Simpson composite integration algorithm in Matlab :

function simps(a, b, n)


%simps(a, b, n) approximates the integral of a function f(x) in the 
%interval [a;b] by the composite simpson rule
%n is the number of subintervals
%the user needs to specify the function f(x) at the bottom

%Author: Alain G. Kapitho
%Date  : Jan 2006

h = (b-a)/n;

sum_even = 0;

for i = 1:n/2-1
   x(i) = a + 2*i*h;
   sum_even = sum_even + f(x(i));
end

sum_odd = 0;

for i = 1:n/2
   x(i) = a + (2*i-1)*h;
   sum_odd = sum_odd + f(x(i));
end

integral = h*(f(a)+ 2*sum_even + 4*sum_odd +f(b))/3


%this needs to be changed accordingly with the specific problem you have at
%hand, before proceeding to the command line
function y = f(x)
y = exp(x);

Composite trapezoidal rule algorithm in Matlab

Composite trapezoidal rule algorithm in Matlab :

function trapez(a, b, n)

%trapez(a, b, n) approximates the integral of a function f(x) in the 
%interval [a;b], by the composite trapezoidal rule
%n is the number of subintervals
%the user needs to specify the function f(x) at the bottom

%Author: Alain G. Kapitho
%Date  : Jan 2006

h = (b-a)/n;

sum = 0;

for i = 1:n-1
   x(i) = a + i*h;
   sum = sum + f(x(i));
end

integral = h*(f(a) + 2*sum + f(b))/2

%this needs to be changed accordingly with the specific problem you have at
%hand, before proceeding to the command line
function y = f(x)
y = 2 + sin(2*sqrt(x));

Newton interpolation method algorithm in Matlab

Newton interpolation method algorithm in Matlab :

function [yy,E,d,n_iter]=interpola_newton(x,y,xx,error)
% Syntaxis: [yy,d,n_iter]=interpola_newton(x,y,xx,error)
% ----------------------------------------------------------------------
% Devuelve el valor interpolado yy en un determinado punto xx solicitado 
% mediante el metodo de las diferencia divididas de Newton, empleando (n-1)
% nodos para la interpolación y un nodo para determinar el error de la 
% interpolacion.
%
% Entrada:
% x     --> Vector que contiene las abcisas de los nodos de interpolacion 
% y     --> Vector que contiene las ordenadas de los nodos de interpolacion
% xx    --> Abcisa del nodo que se desea incorporar
% error --> Tolerancia de la interpolacion {default | 0.05}
%         
%
% Salida: 
% yy     --> Valor interpolado para el nodo con abcisa xx
% E      --> Error real de la interpolacion
% d      --> Tabla de Diferencias Divididas
% n_iter --> Numero de iteraciones necesitadas para verificar la condicion 
%            de parada
%
%
% Ejemplo:
% 
% x=[1.00, 1.05, 1.10, 1.15, 1.20, 1.25, 1.30];
% y=[1.00000, 0.97350, 0.95135, 0.93304, 0.91817, 0.90640, 0.89747];
% xx=1.17; error=0.00005;
% [yy,E,d,n_iter] = interpola_newton(x,y,xx,error)
%
% yy = 0.9267
%  
% E = 2.0944e-05
%  
% d =
% 
%    -0.5300    0.8700   -0.6800    0.7333   -1.3333    6.2222
%    -0.4430    0.7680   -0.5333    0.4000    0.5333         0
%    -0.3662    0.6880   -0.4533    0.5333         0         0
%    -0.2974    0.6200   -0.3467         0         0         0
%    -0.2354    0.5680         0         0         0         0
%    -0.1786         0         0         0         0         0
%  
% n_iter = 4
%
%
% Ver tambien: interpola_lagrange
%
% ----------------------------------------------------------------------
%
% Elaborado por:
%
% Msc. Alexeis Companioni Guerra
% Lic. Vianka Orovio Cobo
%
% Revision: 1.0 
% Fecha: 30/09/2007


%% Validacion de las entradas
if nargin<3
    error('Verifique los datos de entrada.');
elseif nargin<4
    error = 0.05;
end

if min(size(x))>1 || min(size(y))>1
    error('Tanto x como y deben ser vectores.');
elseif max(size(x)) ~= max(size(y))
    error('Verifique la dimension de los vectores.');
else
    x = x(:); y = y(:);
    n = length(x);
end

if sum(size(xx))~=2
   error('La abcisa del nodo de entrada debe ser un escalar.'); 
end

if sum(size(error))~=2
   error('El error maximo de la interpolacion debe ser un escalar.'); 
end

%% Conformacion de las Diferencias Divididas
d = diff(y)./diff(x);
for j=2:n-1
   for k=1:n-j
        d(k,j) = ( d(k+1,j-1) - d(k,j-1) ) / ( x(k+j) - x(k) );
   end
end

%% Seleccion de la primera fila de la matriz de Diferencias Divididas
p = [y(1),d(1,:)];

%% Conformacion iterativa de la solucion 
yy = p(1);
producto = xx-x(1); 
E = p(2)*producto;
i = 2;
while abs(E)>error && i<n
    yy = yy + E;
    producto = producto*(xx-x(i));
    i = i + 1;
    E = p(i)*producto;
end
n_iter = i - 1;

Lagrange interpolation algorithm in Matlab

Lagrange interpolation algorithm in Matlab :

function [yy]=interpola_lagrange(x,y,xx)
% Syntaxis: [yy]=interpola_lagrange(x,y,xx)
% ----------------------------------------------------------------------
% Devuelve el valor interpolado yy en un determinado punto xx solicitado 
% mediante el metodo de interpolacion de Lagrange.
%
% Entrada:
% x  --> Vector que contiene las abcisas de los nodos de interpolacion 
% y  --> Vector que contiene las ordenadas de los nodos de interpolacion
% xx --> Abcisa del nodo que se desea incorporar 
%         
%
% Salida: 
% yy --> Valor interpolado para el nodo con abcisa xx
%
%
% Ejemplo:
% 
% x=[1; 2; 4]; y=[2; 3; 1]; xx=2.5;
% [yy]=interpola_lagrange(x,y,xx)
%
% yy =
%      3
%
%
% Ver tambien: interpola_newton
%
% ----------------------------------------------------------------------
%
% Elaborado por:
%
% Msc. Alexeis Comanioni Guerra
% Lic. Vianka Orovio Cobo
%
% Revision: 1.0 
% Fecha: 30/09/2007


%% Validación de las entradas
if nargin<3
    error('Verifique los datos de entrada.');
end

if min(size(x))>1 || min(size(y))>1
    error('Tanto x como y deben ser vectores.');
else
    x=x(:); y=y(:);
    n=length(x);
end

if sum(size(xx))~=2
   error('La abcisa del nodo de entrada debe ser un escalar.'); 
end

%% Creación de los polinomios de Lagrange
U=ones(n-1,1); 
for i=1:n
    x_temp=x; 
    x_temp(find(x_temp==x_temp(i)))=[];
    L(i)=prod( xx*U-x_temp ) / prod( x(i)*U-x_temp );
end

%% Obtencion del valor interpolado
yy=dot(y,L);

Seidel method algorithm in Matlab

Seidel method algorithm in Matlab :

function [Sol,E,iter,csuf]=seidel(M,b,x0,error,n_iter)
% Syntaxis: [Sol,E,iter,csuf]=seidel(M,b,x0,error,n_iter)
% ----------------------------------------------------------------------
% Esta funcion resuelve un sistema de ecuaciones lineales (SEL) de la
% forma Ax=b por el metodo de Seidel segun
%
% x0 in V (arbitrario)
% x(k+1)=( I-inv(D-E)*A )*x(k) + inv(D-E)*b
%
% Entrada:
% M   --> Matriz del sitema
% b   --> Vector independiente (debe ser un vector columna)
% x0  --> Vector de aproximaciones iniciales
% error  --> Tolerancia del calculo {default | 0.00001}
% n_iter --> Numero maximo de iteraciones {default | 1000} 
%
% Salida: 
% Sol  --> Vector solucion del SEL
% E    --> Error de la aproximacion
% csuf --> Cumplimiento de la condición suficiente de convergencia "alpha<1"
%
%
% Ejemplo:
% 
% M=[9 -1 2; 1 8 2; 1 -1 11]; b=[9; 19; 10];
% [Sol,E,iter,csuf]=seidel(M,b)
%
% Sol =
%      1.0000
%      2.0000
%      1.0000
%
% E = 1.2249e-06
%
% iter = 6
% 
% csuf = 1
%
%
% Ver tambien: jacobi
%
% ----------------------------------------------------------------------
%
% Elaborado por:
%
% Msc. Alexeis Companioni Guerra
% Lic. Vianka Orovio Cobo
%
% Revision: 1.0 
% Fecha: 30/09/2007


%% Validacion de las entradas
if nargin<2
    error('Verifique los datos de entrada.');
else
    if det(M) == 0
        error('M debe ser no singular.');
    end
    
    if diff(size(M))~=0
        error('La matriz de entrada debe ser cuadrada.');
    end
    
    if min(size(b))>1
        error('b debe ser un vector.');
    end
    
    if max(size(M)) ~= max(size(b))
        error('Verifique la dimension del vector independiente respecto a la matriz del sistema.');
    end
end

b = b(:);
n = length(b);

if nargin<3
    x0 = zeros(n,1);
else
    if min(size(x0))>1
        error('x0 debe ser un vector.');
    end
    
    if max(size(M)) ~= max(size(x0))
        error('Verifique la dimension del vector x0 respecto a la matriz del sistema.');
    end
end

if nargin<4
    error = 0.00001;
else
    if sum(size(error))~=2
        error('La tolerancia debe ser un escalar.'); 
    end
end

if nargin<5
    n_iter = 1000;
else
    if sum(size(n_iter))~=2
        error('El numero de iteraciones debe ser un escalar.'); 
    end
    
    if round(n_iter)-n_iter~=0
       error('El numero de iteraciones debe ser un entero.');
    end
end
   
%% Determinacion del factor de convergencia "beta"
Jac = eye(n)-( diag( diag(M).^(-1) )*M ); 
Jac_up = triu(Jac,1); 
Jac_lo = tril(Jac,-1);

beta = max( sum(abs(Jac_up),2) ./ ( ones(n,1)-sum(abs(Jac_lo),2) ) );
if beta>=1
    csuf = 0;
else
    csuf = 1;
end

%% Ciclo iterativo
iter = 0; Sol = zeros(n,1); E = inf; 
s_inv = inv(diag(diag(M)) - tril(M,-1).*(-1));
S = eye(n)-s_inv*M;        % Matriz de Seidel 

while (E>=error) && (iter<n_iter) 
    Sol = S*x0 + s_inv*b;
    E = abs(beta/(1-beta))*norm(Sol-x0,inf);
    x0 = Sol; 
    iter = iter + 1;
end

Jacobi iterative method algorithm in Matlab

Jacobi iterative method algorithm in Matlab :

function jacobi(A, b, N)

%Jacobi(A, b, N) solve iteratively a system of linear equations whereby
%A is the coefficient matrix, and b is the right-hand side column vector.
%N is the maximum number of iterations.
%The method implemented is the Jacobi iterative. 
%The starting vector is the null vector, but can be adjusted to one's needs.
%The iterative form is based on the Jacobi transition/iteration matrix
%Tj = inv(D)*(L+U) and the constant vector cj = inv(D)*b.
%The output is the solution vector x. 

%This file follows the algorithmic guidelines given in the book 
%Numerical Analysis, 7th Ed, by Burden & Faires

%Author: Alain G. Kapitho
%Date  : Dec. 2005
%Rev.  : Aug. 2007

n = size(A,1);
%splitting matrix A into the three matrices L, U and D
D = diag(diag(A));
L = tril(-A,-1);
U = triu(-A,1);

%transition matrix and constant vector used for iterations
Tj = inv(D)*(L+U);
cj = inv(D)*b;

tol = 1e-05;
k = 1;
x = zeros(n,1);   %starting vector

while k <= N
   x(:,k+1) = Tj*x(:,k) + cj;
   if norm(x(:,k+1)-x(:,k)) < tol
      disp('The procedure was successful')
      disp('Condition ||x^(k+1) - x^(k)|| < tol was met after k iterations')
      disp(k); disp('x = ');disp(x(:,k+1));
      break
   end
   k = k+1;
end

if norm(x(:,k+1)- x(:,k)) > tol || k > N
   disp('Maximum number of iterations reached without satisfying condition:')
   disp('||x^(k+1) - x^(k)|| < tol'); disp(tol);
   disp('Please, examine the sequence of iterates')
   disp('In case you observe convergence, then increase the maximum number of iterations')
   disp('In case of divergence, the matrix may not be diagonally dominant')
   disp(x');
end

Gauss-Seidel iterative method algorithm in Matlab

Gauss-Seidel iterative method algorithm in Matlab :

function gauss_seidel(A, b, N)

%Gauss_seidel(A, b, N) solve iteratively a system of linear equations 
%whereby A is the coefficient matrix, and b is the right-hand side column vector.
%N is the maximum number of iterations.
%The method implemented is the Gauss-Seidel iterative. 
%The starting vector is the null vector, but can be adjusted to one's needs.
%The iterative form is based on the Gauss-Seidel transition/iteration matrix
%Tg = inv(D-L)*U and the constant vector cg = inv(D-L)*b.
%The output is the solution vector x.

%This file follows the algorithmic guidelines given in the book 
%Numerical Analysis, 7th Ed, by Burden & Faires

%Author: Alain G. Kapitho
%Date  : Dec. 2005
%Rev.  : Aug. 2007


n = size(A,1);
%splitting matrix A into the three matrices L, U and D
D = diag(diag(A));
L = tril(-A,-1);
U = triu(-A,1);

%transition matrix and constant vector used for iterations
Tg = inv(D-L)*U; 
cg = inv(D-L)*b;

tol = 1e-05;
k = 1;
x = zeros(n,1);   %starting vector

while k <= N
   x(:,k+1) = Tg*x(:,k) + cg;
   if norm(x(:,k+1)-x(:,k)) < tol
      disp('The procedure was successful')
      disp('Condition ||x^(k+1) - x^(k)|| < tol was met after k iterations')
      disp(k); disp('x = ');disp(x(:,k+1));
      break
   end
   k = k+1;
end

if norm(x(:,k+1)- x(:,k)) > tol || k > N
   disp('Maximum number of iterations reached without satisfying condition:')
   disp('||x^(k+1) - x^(k)|| < tol'); disp(tol);
   disp('Please, examine the sequence of iterates')
   disp('In case you observe convergence, then increase the maximum number of iterations')
   disp('In case of divergence, the matrix may not be diagonally dominant')
   disp(x');
end