Está en la página 1de 10

MTODO DE JACOBI PARA SISTEMAS DE ECUACIONES LINEALES

% JACOBI % % X = JACOBI(A,B) % aplica el metodo de Jacobi para la resolucion del sistema AX=B % %[X,IT]= JACOBI(A,B) % devuelve en IT el numero de iteraciones calculadas % %[X,IT,ERRORES]= JACOBI(A,B) % devuelve en ERRORES la diferencia entre iteraciones sucesivas. % Proporciona un historial de la convergencia del mtodo % %[X,IT,ERRORES,FLAG]= JACOBI(A,B,MMAX) % FLAG=1 si hay convergencia, FLAG=0 en caso contrario % %[X,IT,ERRORES,FLAG]= JACOBI(A,B,MMAX,EPS1,EPS2) % EPS1,EPS2 son las tolerancias absoluta y relativa. El mtodo % finaliza si la diferencia entre dos iteraciones sucesivas X1, % X2 cumple norm(X1-X2)<EPS1+norm(X2)*EPS2 % %[X,IT,ERRORES,FLAG]== JACOBI(A,B,MMAX,EPS1,EPS2,X0) % arranca el metodo con X0 % % Extraido del texto: % % "Matlab en cinco lecciones de numerico" % por V. Dominguez y M.L. Rapun. % % Ms informacion en % % http://www.unavarra.es/personal/victor_dominguez function [x, varargout]=jacobi(a,b,varargin) % valores por defecto n=length(a); mmax=100; eps1=1e-4; eps2=1e-4; % tol. absoluta y relativa x=zeros(n,1); if nargin>2 mmax=varargin{1}; end if nargin>3 eps1=varargin{2}; end if nargin>4 eps2=varargin{3}; end if nargin>5 x(:)=varargin{4}; %x es un vector columna end errores=zeros(1,mmax); for m=1:mmax error=0; y=x;

for i=1:n v=[1:i-1 i+1:n]; x(i)=(b(i)-a(i,v)*y(v))/a(i,i); end error=norm(x-y,1); % otras normas con errores(m)=error; % norm(x-y,2),norm(x-y,inf) if (error<eps1+eps2*norm(x)) break end end errores=errores(1:m); if (m==mmax) & nargout<=3 disp('numero maximo de iteraciones sobrepasado') end % salida if (nargout>1) varargout{1}=m; % no de iteraciones end if (nargout>2) varargout{2}=errores; % diferencia entre iteraciones end if (nargout>3) % flag: 1 si hay convergencia, 0 en caso contrario if m==mmax varargout{3}=0; else varargout{3}=1; end end return

MTODO DE JACOBI VERSIN VECTORIZADA


% JACOBIV % % X = JACOBIV(A,B) % aplica el metodo de Jacobi para la resolucion del sistema AX=B % %[X,IT]= JACOBIV(A,B) % devuelve en IT el numero de iteraciones calculadas % %[X,IT,ERRORES]= JACOBIV(A,B) % devuelve en ERRORES el residuo de cada iteracin. % Proporciona un historial de la convergencia del mtodo % %[X,IT,ERRORES,FLAG]= JACOBIV(A,B,MMAX) % FLAG=1 si hay convergencia, FLAG=0 en caso contrario % %[X,IT,ERRORES,FLAG]= JACOBIV(A,B,MMAX,EPS1,EPS2) % EPS1,EPS2 son las tolerancias absoluta y relativa. El mtodo % finaliza si norm(B-A*X)<EPS1+norm(B)*EPS2 %

%[X,IT,ERRORES,FLAG]== JACOBIV(A,B,MMAX,EPS1,EPS2,X0) % arranca el metodo con X0 % % Versin vectorizada % % Extraido del texto: % % "Matlab en cinco lecciones de numerico" % por V. Dominguez y M.L. Rapun. % % Ms informacion en % % http://www.unavarra.es/personal/victor_dominguez function [x, varargout]=jacobiv(a,b,varargin) % valores por defecto n=length(a); mmax=100; eps1=1e-4; eps2=1e-4; % tol. absoluta y relativa x=zeros(n,1); if nargin>2 mmax=varargin{1}; end if nargin>3 eps1=varargin{2}; end if nargin>4 eps2=varargin{3}; end if nargin>5 x(:)=varargin{4}; %x es un vector columna end errores=zeros(1,mmax); d=diag(a); r=(b-a*x); normab=norm(b); for m=1:mmax x=x+r./d; r=(b-a*x); % residuo normar=norm(r); errores(m)=normar; % norm(x-y,2),norm(x-y,inf) if (normar<eps1+eps2*normab) break end end errores=errores(1:m); if (m==mmax) & nargout<=3 disp('numero maximo de iteraciones sobrepasado') end % salida if (nargout>1) varargout{1}=m; % no de iteraciones end if (nargout>2) varargout{2}=errores; % diferencia entre iteraciones end

if (nargout>3) % flag: 1 si hay convergencia, 0 en caso contrario if m==mmax varargout{3}=0; else varargout{3}=1; end end return

MTODO DE JACOBI EXTRA

%Hecho con un menu-metodo de jacobi y gauss seidel %Hecho por JUAN LOPEZ MONTEJO %INSTITUTO TECNOLOGICO SUPERIOR DE LOS RIOS function menujacobiyseidel=menujacobiyseidel() format long disp('================================================================') disp('==POR FAVOR,INGRESE LA MATRIZ QUE SE LE PIDA DE FORMA ORDENADA=='); disp('================================================================') e=input('CUANTAS ECUACIONES:'); A=input('INGRESE LA MATRIZ A:'); b=input('INGRSE LA MATRIZ b:'); disp('HOLA, POR CUAL METODO DESEA RESOLVER EL SISTEMA'); disp('========================'); disp('== MENU =='); disp('== 1.- JACOBI =='); disp('== 2.- GAUSS-SEIDEL =='); disp('== 3.- Salir =='); disp('========================'); t=input('ELIJA SOLO UNA OPCION:'); m=input('CUANTAS ITERACIONES DESEA HACER:'); if t==1 x0=zeros(1,e);k=0;norma=1; while norma>0.00000001 k=k+1;fprintf('%2d',k) for i=1:e suma=0; for j=1:e if i ~=j suma=suma+A(i,j)*x0(j); end end x(i)=(b(i)-suma)/A(i,i);fprintf('%10.4f',x(i)) end norma=norm(x0-x);fprintf('%10.4fn',norma) x0=x; if k>m break end end

elseif t==2 XO=zeros(1,e);X=XO; K=0;Norma=1; while Norma>0.00001 K=K+1; fprintf ('%d', K) for i=1:e suma=0; for j=1:e if i ~= j suma=suma+A(i,j)*X(j); end end X(i)=(b(i)-suma)/A(i,i); fprintf ('%10.6f',X(i)) end Norma=norm(XO-X); fprintf('%10.6fn',Norma) X0=X; if K>m end end end end break

elseif t>3 disp('POR FAVOR VERIFIQUE,LA OPCION QUE USTED ESCOGIO NO EXISTE.');

MTODO DE JACOBI

function[]=jacobi(y,v) %funcion que soluciona un sistema de ecuaciones simultaneas [r,c]=size(y);%r guarda el numero de renglones y c el numero de columnas d=diag(y);%d sera un vector el cual contendra los elementos de la %diagonal principal de la matriz formada por el sistema %de ecuaciones h=0;%h servira de contador z=0;%z sera el valor que usaremos para condicionar k=0; for i=1:r%Inicio de despeje de incognitas for j=1:c if j~=i x(i,j)=[-y(i,j)./d(i)];%x sera una matriz la cual contendra %en sus renglones nuestras incognitas %despejadas end end end %incognitas despejadas while z~=1%ciclo que se repetira hasta encontrar el valor de las incognitas for i=1:r%este ciclo nos servira para controlar el numero de %renglon en que se este analizando y asi evaluar las

%incognitas %despejadas y obtener los nuevos valores que se utilizaran %para evaluar dichas incognitas f(i)=0;%la posicion i del vector f se le asignara cero %para evitar una acomulacion for j=1:c%ciclo que nos servira para encontrar los nuevos valores %en los que se evaluara nuestras incognitas if j~=c%condicion para evitar multiplicar el valor constante f(i)=f(i)+(x(i,j).*v(j));%el vector f tomara los nuevos %valores en los se volveran a %evaluar las incognitas despejadas else f(i)=f(i)+(x(i,j)); end end end for i=1:r if f(i)==v(i)%se comparan los valores del vector f con los %del vector v h=h+1;%si se cumple la condicion el contador aumenta end end for i=1:r v(i)=f(i);%el vector v adquiere los nuevos valores obtenidos %anteriormente end if h==r z=1;%si el contador es igual al numero de renglones quiere decir %que los valores utilizados anteriormente son iguales a los %acabados de obtener else h=0;%si no el contador regresa a cero end MTODO DE JACOBI
%metodo de jacobi %Hecho por JUAN LOPEZ MONTEJO %INSTITUTO TECNOLOGICO SUPERIOR DE LOS RIOS function jacobi=jacobi r=input('cuantas A=input('ingrese b=input('ingrese H=input('cuantas ecuaciones'); la matriz A:'); la matriz b:'); iteraciones:'); X(2) X(3) X(4) Norman')

X0=zeros(1,r);K=0;Norma=1; fprintf(' K X(1) while Norma>0.0001

K=K+1; fprintf('%2d',K) for i=1:r suma=0; for j=1:r if i ~=j suma=suma+A(i,j)*X0(j); end end X(i)=(b(i)-suma)/A(i,i); fprintf('%10.6f',X(i)) end Norma=norm(X0-X);fprintf('%10.6fn',Norma) X0=X; if K>=H end end break

MTODO DE JACOBI
function x = jacobi ( A, b, xold, TOL, Nmax ) %JACOBI % % % calling % % % % inputs: % % % % % % % % % % output: % % % NOTE: % % % % % % % % approximate the solution of the linear system Ax = b by applying the Jacobi method (simultaneous relaxation) sequences: x = jacobi ( A, b, xold, TOL, Nmax ) jacobi ( A, b, xold, TOL, Nmax ) A b xold TOL NMax x coefficient matrix for linear system - must be a square matrix right-hand side vector for linear system vector containing initial guess for solution of linear system convergence tolerance - applied to maximum norm of difference between successive approximations maximum number of iterations to be performed approximate solution of linear system

if JACOBI is called with no output arguments, the iteration number and the current approximation to the solution are displayed if the maximum number of iterations is exceeded, a meesage to this effect will be displayed and the current approximation will be returned in the output value

n = length ( b );

[r c] = size ( A ); if ( c ~= n ) disp ( 'jacobi error: matrix dimensions and vector dimension not compatible' ) return end; xnew = zeros ( 1, n ); if ( nargout == 0 ) s = sprintf ( '%3d \t %10f ', 0, xold(1) ); for j = 2 : n s = sprintf ( '%s%10f ', s, xold(j) ); end; disp ( s ); end; for its = 1 : Nmax xnew(1) = ( b(1) - sum ( A(1,2:n) .* xold(2:n) ) ) / A(1,1); for i = 2 : n-1 xnew(i) = ( b(i) - sum ( A(i,1:i-1) .* xold(1:i-1) ) - sum ( A(i,i+1:n) .* xold(i+1:n) ) ) / A(i,i); end; xnew(n) = ( b(n) - sum ( A(n,1:n-1) .* xold(1:n-1) ) ) / A(n,n); if ( nargout == 0 ) s = sprintf ( '%3d \t %10f ', its, xnew(1) ); for j = 2 : n s = sprintf ( '%s%10f ', s, xnew(j) ); end; disp ( s ); end; conv = max ( abs ( xnew - xold ) ); if ( conv < TOL ) x = xnew; return else xold = xnew; end; end; disp ( 'jacobi error: maximum number of iterations exceeded' ); if ( nargout == 1 ) x = xnew; end;

MTODO DE JACOBI

function y = jacobi (A,b,y,N) % This function applies N iterations of Jacobi's method % to the system of linear equations Ax = b. y=[0,0,0,0]'; n = length(y); for k=1:N for i=1:n sum = b(i); for j=1:i-1 sum = sum - A(i,j)*y(j); end for j = i+1:n sum = sum - A(i,j)*y(j); end x(i) = sum/A(i,i); end y = x'; end

MTODO DE JACOBI MEJORADO

function [x, error, iter, flag] = jacobi(A, x, b, max_it, tol) % -- Iterative template routine -% Univ. of Tennessee and Oak Ridge National Laboratory % October 1, 1993 % Details of this algorithm are described in "Templates for the % Solution of Linear Systems: Building Blocks for Iterative % Methods", Barrett, Berry, Chan, Demmel, Donato, Dongarra, % Eijkhout, Pozo, Romine, and van der Vorst, SIAM Publications, % 1993. (ftp netlib2.cs.utk.edu; cd linalg; get templates.ps). % % [x, error, iter, flag] = jacobi(A, x, b, max_it, tol) % % jacobi.m solves the linear system Ax=b using the Jacobi Method. % % input A REAL matrix % x REAL initial guess vector % b REAL right hand side vector % max_it INTEGER maximum number of iterations % tol REAL error tolerance %

% output % % % %

x error iter flag

REAL solution vector REAL error norm INTEGER number of iterations performed INTEGER: 0 = solution found to tolerance 1 = no convergence given max_it % initialization

iter = 0; flag = 0; bnrm2 = norm( b ); if ( bnrm2 == 0.0 ), bnrm2 = 1.0; end r = b - A*x; error = norm( r ) / bnrm2; if ( error < tol ) return, end [m,n]=size(A); [ M, N ] = split( A , b, 1.0, 1 ); for iter = 1:max_it, x_1 = x; x = M \ (N*x + b); error = norm( x - x_1 ) / norm( x ); if ( error <= tol ), break, end end if ( error > tol ) flag = 1; end % END jacobi.m

% matrix splitting % begin iteration % update approximation % compute error % check convergence

% no convergence

También podría gustarte