Monday, May 27, 2013

Gauss Jordan Elimination & Pivoting algorithm in Matlab

Gauss Jordan Elimination & Pivoting algorithm in Matlab :

%Gauss Jordan elimination with pivoting
%copy this file to the command window and press enter
%Bangladesh University of Engineering & Technology
%Nadim Chowdhury
%Department Of Electrical & Electronics Engineering
%if You have any problem in understanding this  feel free to e-mail me At
%nadim_eee_buet@yahoo.com
A=0;
x=0;
n=input('How many variables=');
disp('Enter the coefficients along with constants For instance if x+y+3z=-5 then enter 1 1 3 -5 each number followed by an enter not space');
for i=1:n
    for j=1:n+1
        A(i,j)=input('');
    end
end
%pivoting
for i=1:n-1
    for j=i+1:n
        if abs(A(j,i))>abs(A(i,i))
            T=A(j,:);
            A(j,:)=A(i,:);
            A(i,:)=T;
        end
    end
end
disp('After pivoting');
disp(A);
for k=1:n-1
    for i=k+1:n
        m=A(i,k)/A(k,k);
        for j=k:n+1
            A(i,j)=A(i,j)-m*A(k,j);
        end
    end
end
disp('Triangularize Form  ');
disp(A);
            
if A(n,n)==0
    disp('No unique solution');
end
    x(n)=A(n,n+1)/A(n,n);
    for j=n-1:-1:1
        sum=0;
    for i=1:n
        sprintf('x%.0f=%.10f',i,x(i))
    end
        

        for i=1:n-j
            sum=sum+A(j,n+1-i)*x(n+1-i);
        end
        x(j)=(A(j,n+1)-sum)/A(j,j);
    end    

Newton Method algorithm in Matlab

Newton Method algorithm in Matlab :

function [xvect,xdif,fx,nit]=mynewton(x0,nmax,fun,dfun,toll);
% MYNEWTON   Do the newton iteration to find the zeros of the given
% inline scalar function. 
%    [XVEC,XDIF,FX,NIT] = MYNEWTON(X0,NMAX,FUN,DFUN,TOLL)  
%       Input:  x0: starting value
%             nmax: maximum number of iteration
%             toll: tolerance, default is 1e-10
%              fun: given inline function
%             dfun: derivative of the function given as inline
%             function 
%
%    Output: xvect: stores values in all iterations (arg)
%             xdif: difference between two consequent values (arg) 
%               fx: stores function values  in all iterations 
%              nit: number of iteration required
%
%      Examples:
%         The first examples converge to unique zero
%            fun=inline('x^3+x^2-4');  x0=0.3; nmax=100;
%           dfun=inline('3*x^2+2*x');
%
%            fun=inline('x^4+x^3-5*x-12'); 
%           dfun=inline('4*x^3+3*x^2-5');
%
%            fun=inline('x^5+10*x^2-9*x+10');
%           dfun=inline('5*x^4+20*x-9');
%
%         Examples where different starting values converge to
%         different zeros
%            fun=inline('x^2-4*sin(x)');
%           dfun=inline('2*x-4*cos(x)');
%
%            fun=inline('x^3+x^2*(cos(x))^2-4');
%           dfun=inline('(3*x^2+2*x*cos(x)^2-2*x^2*cos(x)*sin(x))');
 
% Author: Bishnu Lamichhane, University of Stuttgart

if (nargin==4)  toll=1e-10; end

err=toll+1; nit=0; xvect=x0;x=x0;fx=feval(fun,x);xdif=[];
  while(nit<nmax & err>toll)
    nit=nit+1; x=xvect(nit);dfx=feval(dfun,x);
    if (dfx==0), err=toll*1e-10;
      disp('Stop for vanishing dfun');
    else,
      xn=x-fx(nit)/dfx;err=abs(xn-x);xdif=[xdif;err];
      x=xn;xvect=[xvect;x];fx=[fx;feval(fun,x)];
    end
  end
n=1:nit;
plot(n, xdif, '-*');
title(['Plot of error with respect to iteration, f(x)=',char(fun)]);
xc = get(gca,'XLim');
yc = get(gca,'YLim');
xc = (xc(1)+xc(2))/2;
text(xc,yc(2)*0.9,['x_{zero} = ',num2str(x),'; x_{start} =' , ...
          num2str(x0)], 'HorizontalAlignment', 'center'); 

Secant Method algorithm in Matlab

Secant Method algorithm in Matlab :

function [xvect,xdif,fx,nit] = secant(x1,x0,nmax,fun,toll);
% SECANT   Do the secant iteration to find the zeros of the given
% inline scalar function and its derivative. 
%    [XVEC,XDIF,FX,NIT] = SECANT(X1,X0,NMAX,FUN,TOLL)  
%       Input:x0 and x1 starting value
%             nmax: maximum number of iteration
%             toll: tolerance, default is 1e-10
%             fun: given inline function
%
%      Output: xvect: stores values in all iterations (arg)
%              xdif : difference between two successive values
%              (arg) 
%              fx: stores function values  in all iterations 
%              nit: number of iteration required
%
%     Examples:
%          fun=inline('x^3+x^2-4'); x0=0.3;x1=0.5; nmax=100;
%          fun=inline('x^5+10*x^2-9*x+10');

% Author: Bishnu Lamichhane, University of Stuttgart

if (nargin==4)  toll=1e-10; end
x=x1;
fx1=feval(fun,x);
xvect=[x];
 fx=[fx1];
 x=x0;
 fx0=feval(fun,x);
 xvect=[xvect;x];fx=[fx;fx0];err=toll+1;nit=0;xdif=[];
 while(nit<nmax & err>toll)
   nit=nit+1;
   if (abs(fx0-fx1)<eps)
     err=toll*1e-10;
     disp('Stop for vanishing dfun');
   else
     x=x0-fx0*(x0-x1)/(fx0-fx1);
     xvect=[xvect;x];
   fnew=feval(fun,x);
   fx=[fx;fnew];
   err=abs(x0-x);
   xdif=[xdif;err];
   x1=x0;fx1=fx0;x0=x;fx0=fnew;
   end;
 end;
n=1:nit;
plot(n, xdif, '-*');
title(['Plot of error with respect to iteration, f(x)=',char(fun)]);
xc = get(gca,'XLim');
yc = get(gca,'YLim');
xc = (xc(1)+xc(2))/2;
text(xc,yc(2)*0.9,['x_{zero} = ',num2str(x)], ...
          'HorizontalAlignment', 'center'); 

Regula-Falsi method algorithm in Matlab

Regula-Falsi method algorithm in Matlab :

function [c,E,fc]=regula(f,a,b,error,n_iter)
% syntaxis: [c,E,fc]=regula(f,a,b,error,n_iter)
% ---------------------------------------------------------------------
% Esta funcion permite determinar de manera aproximada el valor de la
% raiz de una ecuacion no lineal f(x)=0 mediante el metodo de Regula-Falsi.
% De manera adicional se proporciona una tabla con el valor de la 
% aproximacion y el error corespondiente en cada iteracion.
%
% Entrada:
% f      --> Funcion simbolica
% a, b   --> Extremos del intervalo
% error  --> Tolerancia del calculo {default | 0.00001}
% n_iter --> Numero maximo de iteraciones {default | 1000}
%
% Salida:
% c  --> Aproximacion encontrada
% E  --> Error de la aproximacion "c"
% fc --> Valor de la funcion en la aproximacion
%
%
% Ejemplo:
% 
% f=sym('x^2-1'); 
% [c,E,fc]=regula(f,0,3,0.005,20);
%
% --------|----------|------------|
% Iter.       Aprox.     Error.   
% --------|----------|------------|
% ini        0.3333      3.0000       
% 1          0.6000      0.2667       
% 2          0.7778      0.1778       
% 3          0.8824      0.1046       
% 4          0.9394      0.0570       
% 5          0.9692      0.0298       
% 6          0.9845      0.0153       
% 7          0.9922      0.0077       
% 8          0.9961      0.0039       
% --------|----------|------------|
%
% c = 0.9961
%
% E = 0.0039
%
% fc = -0.0078
%
%
% Ver tambien: biseccion
%
% ----------------------------------------------------------------------
%
% Elaborado por:
%
% Msc. Alexeis Comanioni Guerra
% Lic. Vianka Orovio Cobo
%
% Revision: 1.0 
% Fecha: 30/09/2007


%% Validacion de la entrada
if (nargin<3)  
    error('Revise los datos de entrada.');
else
    tipo = class(f);
    if all( (tipo(1:3)=='sym')>0 )~=1
        error('La funcion f debe ser simbolica.');
    end
    
    if sum(size(a))~=2 || sum(size(b))~=2
        error('Los extremos del intervalo deben ser escalares.'); 
    end  
end

if (nargin<4) 
    error=0.00001;
    n_iter=1000;
elseif (nargin<5) 
    n_iter=1000;
    if sum(size(error))~=2
        error('La tolerancia debe ser un escalar.'); 
    end
else
    if sum(size(error))~=2
        error('La tolerancia debe ser un escalar.'); 
    end
    
    if round(n_iter)-n_iter~=0
        error('El numero de iteraciones debe ser un entero.');
    end
end

%% Teorema de Bolzano
if subs(f,a)*subs(f,b)>0
 error('Imposible de aplicar el metodo: note que --> f(a)*f(b)>0');
end

%% Metodo de Regula-Falsi
x= a - (subs(f,a)*(b-a)/(subs(f,b)-subs(f,a))); 
E=b-a;
RES(1,1)=x; ERR(1,1)=E;
xa=x; i=1;
while (E>=error) && (i<n_iter)
    if subs(f,x)==0
        fprintf('La raiz es exactamente: %f',x);
        break;
 elseif subs(f,b)*subs(f,x)<0
     a=x; %b=b;
 else
     b=x; %a=a;
    end
    x= a - (subs(f,a)*(b-a)/(subs(f,b)-subs(f,a)));
    E= abs(x-xa);
    xa=x; i=i+1;
    RES(i,1)=x; ERR(i,1)=E;
end

%% Formateo de las salidas
disp('--------|----------|------------|');
fprintf('Iter.       Aprox.     Error.   \n');
disp('--------|----------|------------|');
fprintf('%-10s %-11.4f %-12.4f \n','ini',RES(1,1),ERR(1,1));
for i=2:max(size(RES))
    fprintf('%-10.0d %-11.4f %-12.4f \n',i-1,RES(i,1),ERR(i,1));
end
disp('--------|----------|------------|');

c=x; fc=subs(f,x);

The Fixed-point iteration algorithm in Matlab

The Fixed-point iteration algorithm in Matlab :

function fixed_point(p0, N)

%Fixed_Point(p0, N) approximates the root of the equation f(x) = 0
%rewritten in the form x = g(x), starting with an initial approximation p0. 
%The iterative technique is implemented N times.
%The user has to enter the function g(x)at the bottom


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

i = 1;
p(1) = p0;
tol = 1e-05;
while i <= N
   p(i+1) = g(p(i));
   if abs(p(i+1)-p(i)) < tol  %stopping criterion
      disp('The procedure was successful after k iterations')
      k = i
      disp('The root to the equation is')
      p(i+1)
      return
   end
   i = i+1;
end

if abs(p(i)-p(i-1)) > tol | i > N
   disp('The procedure was unsuccessful')
   disp('Condition |p(i+1)-p(i)| < tol was not sastified')
   tol
   disp('Please, examine the sequence of iterates')
   p = p'
   disp('In case you observe convergence, then increase the maximum number of iterations')
   disp('In case of divergence, try another initial approximation p0 or rewrite g(x)')
   disp('in such a way that |g''(x)|< 1 near the root')
end

%this part has to be changed accordingly with the specific function g(x)
function y = g(x)
%y = x - x.^3 - 4*x.^2 + 10;
%y = sqrt(10./x - 4*x);
y = x - (x.^3 + 4*x.^2 - 10)/(3*x.^2 + 8*x);

Algorithm of Bisection method in Mtalab

Algorithm of Bisection method in Mtalab :

function [c,E,fc]=biseccion(f,a,b,error,n_iter)
% syntaxis: [c,E,fc]=biseccion(f,a,b,E,n_iter)
% ---------------------------------------------------------------------
% Esta funcion permite determinar de manera aproximada el valor de la
% raiz de una ecuacion no lineal f(x)=0 mediante el metodo de Biseccion.
% De manera adicional se proporciona una tabla con el valor de la 
% aproximacion y el error corespondiente en cada iteracion.
%
% Entrada:
% f      --> Funcion simbolica
% a, b   --> Extremos del intervalo
% error  --> Tolerancia del calculo {default | 0.00001}
% n_iter --> Numero maximo de iteraciones {default | 1000}
%
% Salida:
% c  --> Aproximacion encontrada
% E  --> Error de la aproximacion "c"
% fc --> Valor de la funcion en la aproximacion
%
%
% Ejemplo:
% 
% f=sym('x^2-1'); 
% [c,E,fc]=biseccion(f,0,3,0.005,20);
%
% --------|----------|------------|
% Iter.       Aprox.     Error.   
% --------|----------|------------|
% ini        1.5000      1.5000       
% 1          0.7500      0.7500       
% 2          1.1250      0.3750       
% 3          0.9375      0.1875       
% 4          1.0313      0.0938       
% 5          0.9844      0.0469       
% 6          1.0078      0.0234       
% 7          0.9961      0.0117       
% 8          1.0020      0.0059       
% 9          0.9990      0.0029       
% --------|----------|------------|
%
% c = 0.9990
%
% E = 0.0029
%
% fc = -0.0020
%
%
% Ver tambien: regula
%
% ----------------------------------------------------------------------
%
% Elaborado por:
%
% Msc. Alexeis Comanioni Guerra
% Lic. Vianka Orovio Cobo
%
% Revision: 1.0 
% Fecha: 30/09/2007


%% Validacion de la entrada
if (nargin<3)  
    error('Revise los datos de entrada.');
else
    tipo = class(f);
    if all( (tipo(1:3)=='sym')>0 )~=1
        error('La funcion f debe ser simbolica.');
    end

    if sum(size(a))~=2 || sum(size(b))~=2
        error('Los extremos del intervalo deben ser escalares.'); 
    end  
end

if (nargin<4) 
    error=0.00001;
    n_iter=1000;
elseif (nargin<5) 
    n_iter=1000;
    if sum(size(error))~=2
        error('La tolerancia debe ser un escalar.'); 
    end
else
    if sum(size(error))~=2
        error('La tolerancia debe ser un escalar.'); 
    end
    
    if round(n_iter)-n_iter~=0
        error('El numero de iteraciones debe ser un entero.');
    end
end

%% Teorema de Bolzano
if subs(f,a)*subs(f,b)>0
    error('Imposible de aplicar el metodo: note que --> f(a)*f(b)>0');
end

%% Metodo de Biseccion
x=(a+b)/2; E=(b-a)/2;
RES(1,1)=x; ERR(1,1)=E;
i=1;
while (E>=error) && (i<=n_iter)
    if subs(f,x)==0
        fprintf('La raiz es exactamente: %f',x);
        break;
    elseif subs(f,b)*subs(f,x)<0
 a=x; %b=b;
    else
 b=x; %a=a;
    end
    x=(a+b)/2; E=(b-a)/2;
    i=i+1;
    RES(i,1)=x; ERR(i,1)=E;
end

%% Formateo de las salidas
disp('--------|----------|------------|');
fprintf('Iter.      Aprox.      Error.   \n');
disp('--------|----------|------------|');
fprintf('%-10s %-11.4f %-12.4f \n','ini',RES(1,1),ERR(1,1));
for i=2:max(size(RES))
    fprintf('%-10.0d %-11.4f %-12.4f \n',i-1,RES(i,1),ERR(i,1));
end
disp('--------|----------|------------|');

c=x; fc=subs(f,x);

Sunday, May 26, 2013

The LU Decomposition algorithm in Matlab

The LU Decomposition algorithm in Matlab :

function [L,U,P] = lu_dcmp(A)
%This gives LU decomposition of A with the permutation matrix P
% denoting the row switch(exchange) during factorization
NA = size(A,1);
AP = [A eye(NA)]; %augment with the permutation matrix.
for k = 1:NA - 1
%Partial Pivoting at AP(k,k)
[akx, kx] = max(abs(AP(k:NA,k)));
if akx < eps
error(’Singular matrix and No LU decomposition’)
end
mx = k+kx-1;
if kx > 1 % Row change if necessary
tmp_row = AP(k,:);
AP(k,:) = AP(mx,:);
AP(mx,:) = tmp_row;
end
% LU decomposition
for m = k + 1: NA
AP(m,k) = AP(m,k)/AP(k,k); %Eq.(2.4.8.2)
AP(m,k+1:NA) = AP(m,k + 1:NA)-AP(m,k)*AP(k,k + 1:NA); %Eq.(2.4.9)
end
end
P = AP(1:NA, NA + 1:NA + NA); %Permutation matrix
for m = 1:NA
for n = 1:NA
if m == n, L(m,m) = 1.; U(m,m) = AP(m,m);
elseif m > n, L(m,n) = AP(m,n); U(m,n) = 0.;
else L(m,n) = 0.; U(m,n) = AP(m,n);
end
end
end
if nargout == 0, disp(’L*U = P*A with’); L,U,P, end
%You can check if P’*L*U = A?