Gauss_Seidel_Method_for_NxN_System

Gauss Seidel method for NxN system

clc; clear all;
A=input('Enter the coefficient matrix:');
B=input('Enter the constant matrix:');
x0=input('Enter initial values of variables:');
err=input('Enter the allowable error:');
B=B';
x0=x0';
Z=size(A,1);
x=x0;
kmax=1000;
for k=1:kmax
    x(1,:)=(B(1,:)-A(1,2:Z)*x(2:Z,:))/A(1,1);
    for m=2:Z-1
        tmp=B(m,:)-A(m,1:m-1)*x(1:m-1,:)-A(m,m+1:Z)*x(m+1:Z,:);
        x(m,:)=tmp/A(m,m);
    end
    x(Z,:)=(B(Z,:)-A(Z,1:Z-1)*x(1:Z-1,:))/A(Z,Z);
   
    if abs(x-x0)<err
        break;
    end
    x0=x;
end
disp('The solutions are:')
disp(x)
fprintf('k=%d',k);

Comments