gaussseidel in matlab

Gauss Seidel method can be implemented in MATLAB using a loop that updates the solution vector iteratively. Here is a sample code which solves the system of linear equations Ax=b using Gauss Seidel method:

main.m
% Initialize the matrix A and vector b
A = [4,-1,0; -1,4,-1; 0,-1,3];
b = [12; 15; 10];

% Set the initial guess for solution
x0 = [0; 0; 0];

% Set the tolerance and maximum number of iterations
tol = 1e-6;  % relative error tolerance
maxit = 100; % maximum number of iterations

% Initialize the solution vector and the iteration counter
x = x0;
iter = 0;

% Gauss Seidel iteration loop
while(iter < maxit)
    xold = x;
    for i = 1:length(x)
        sigma = 0;
        for j = 1:length(x)
            if (j ~= i)
                sigma = sigma + A(i,j)*x(j);
            end
        end
        x(i) = (1/A(i,i))*(b(i) - sigma);
    end
    % Check for convergence
    if (norm(x-xold)/norm(xold) < tol)
        break;
    end
    iter = iter+1;
end

% print the result
fprintf('The solution is: x = %f, %f, %f\n', x(1), x(2), x(3));
fprintf('Number of iterations = %d\n', iter);
884 chars
38 lines

The code can be adapted for the specific system of linear equations by changing the matrix A, vector b and initial guess x0. The tolerance and maximum number of iterations can also be adjusted according to the desired accuracy and computational resources. Note that the convergence of Gauss Seidel method depends on the matrix A, and it may not converge for some matrices.

gistlibby LogSnag