J.c
J.c

Reputation: 11

Jacobi iteration to Gauss-Seidel

I have the following function written for the Jacobi method and need to modify it to perform Gauss-Seidel

function [ x,iter] = jacobi( A,b,tol,maxit )
%jacobi iterations
%   

x=zeros(size(b));

[n,m]=size(A);

i=1;

iter=maxit;

for i=1:maxit

    for j=1:n

        y(j)=(b(j)-A(j,1:j-1)*x(1:j-1)-A(j,j+1:n)*x(j+1:n))/A(j,j)

    end

    if max(abs(A*y'-b))<tol
        iter=i;
        break;
    end
    x=y';

end

I know I need to get x(1:j-1) to update but am unsure of how to write it, thanks

Upvotes: 1

Views: 19514

Answers (2)

zubair
zubair

Reputation: 1

function [x succes iter]=gausssedel(A,b,x0,tol,maxiter)

n=length(A);
succes=0;
iter=maxiter;
x=zeros(n,1);

while maxiter > 0
    maxiter=maxiter-1;
    for i=1:n
       % suma=A(i,1:i-1)*x(i,1-i)+A(i,i+1:n)*x0(i+1:n);
         suma=A(i,1:i-1)*x(1:i-1)+A(i,i+1:n)*x0(i+1:n);
        x(i) = (b(i)-suma)/A(i,i);
    end
    if norm(x-x0) < tol
        succes=1;
        break;
    end
    x0=x;

end
iter=iter-maxiter;
end

Upvotes: 0

Lutz Lehmann
Lutz Lehmann

Reputation: 25972

You just simply have to get rid of y and replace any occurrence of y with x.

for j=1:n

    x(j)=(b(j)-A(j,1:j-1)*x(1:j-1)-A(j,j+1:n)*x(j+1:n))/A(j,j)

end

if max(abs(A*x-b))<tol
    iter=i;
    break;
end

Jacobi computes a new vector from the old and then replaces all variables at once.

Gauß-Seidel computes in-place and uses always the most current values.

Upvotes: 2

Related Questions