gauss seidel iteration solver in matlab

The Gauss-Seidel iteration method is an iterative way to solve linear systems of equations. Here is an implementation in MATLAB:

main.m
function [x,convergence] = gauss_seidel(A,b,x0,max_iter,tol)
% This function implements Gauss-Seidel iteration method
% to solve linear systems of equations: Ax = b
% Arguments:
% A: matrix of coefficients
% b: column matrix of constants
% x0: initial guess
% max_iter: maximum number of iterations allowed
% tol: tolerance
% Returns:
% x: solution vector
% convergence: vector of residuals indicating convergence
n = size(A,1);
x = x0;
for k = 1:max_iter
    for i = 1:n
        s = 0;
        for j = 1:i-1
            s = s + A(i,j) * x(j);
        end
        for j = i+1:n
            s = s + A(i,j) * x0(j);
        end
        x(i) = ( b(i) - s ) / A(i,i);
    end
    convergence(k) = norm( A*x - b );
    if convergence(k) < tol
        break;
    end
    x0 = x;
end
end
781 chars
33 lines

Here is an example of how to use it:

main.m
% define matrix A and column matrix b
A = [  4, -1,  0,  0;
      -1,  4, -1,  0;
       0, -1,  4, -1;
       0,  0, -1,  3 ];
b = [ 19;
      4;
     11;
     10 ];
% set initial guess and maximum number of iterations
x0 = [ 0;
       0;
       0;
       0 ];
max_iter = 100;
tol = 1e-6;
% solve the system using Gauss-Seidel iteration method
[x,convergence] = gauss_seidel(A,b,x0,max_iter,tol);
% print the solution
disp(['Solution:']);
disp(x);
% plot convergence
semilogy(1:length(convergence),convergence);
title('Convergence of Gauss-Seidel method');
xlabel('Iteration');
ylabel('Residual');
599 chars
27 lines

Hope this helps!

related categories

gistlibby LogSnag