solving 6 linear system of equations using gauss-seidel iterative solver in matlab

To solve a system of linear equations using Gauss-Seidel iterative solver in Matlab, you can follow the steps below:

  1. Define the coefficient matrix A and the constant vector b.
  2. Initialize the solution vector x with an initial guess.
  3. Set the convergence tolerance tol and the maximum number of iterations maxit.
  4. Implement the Gauss-Seidel iteration using a while loop. The iteration stops when the maximum number of iterations is reached or the norm of the residual vector is less than the convergence tolerance. The Gauss-Seidel iteration can be written as follows:
main.m
for k = 1:maxit
    for i = 1:length(b)
        sigma = A(i,1:i-1)*x(1:i-1) + A(i,i+1:end)*x(i+1:end);
        x(i) = (b(i) - sigma)/A(i,i);
    end
    if norm(A*x-b) < tol
        break
    end
end
200 chars
10 lines
  1. Return the solution x.

Here is the complete code:

main.m
A = [4 -1 0 0 0 0;
    -1 4 -1 0 0 0;
    0 -1 4 -1 0 0;
    0 0 -1 4 -1 0;
    0 0 0 -1 4 -1;
    0 0 0 0 -1 3];
b = [15;10;10;10;10;10];
x = [0;0;0;0;0;0];
tol = 1e-6;
maxit = 1000;

for k = 1:maxit
    for i = 1:length(b)
        sigma = A(i,1:i-1)*x(1:i-1) + A(i,i+1:end)*x(i+1:end);
        x(i) = (b(i) - sigma)/A(i,i);
    end
    if norm(A*x-b) < tol
        break
    end
end

x
388 chars
23 lines

This code solves the following system of linear equations:

main.m
4x1 - x2 = 15
-x1 + 4x2 - x3 = 10
-x2 + 4x3 - x4 = 10
-x3 + 4x4 - x5 = 10
-x4 + 4x5 - x6 = 10
-x5 + 3x6 = 0
108 chars
7 lines

gistlibby LogSnag