%%%%%%%% GAUSS-SEIDEL METHOD %%%%%%%%%%

%%%% HAVE TO CHECK MAX ERROR MANUALLY - CODE WILL PRINT MORE ITERATIONS %%%%


% Define the matrix A and vector b
A = [8, 0, 6; -1, 12, 0; -7, -0.5, 15];
b = [25; 7; -14];

% Initial guess
x0 = [0; 1; 1];

% Maximum allowed component-wise error percentage
max_error_percentage = 5;

% Initialize variables
x = x0;
n = length(b);
tolerance = max_error_percentage / 100;

% Display the header for the iteration table
fprintf('Iteration\t x1\t\t x2\t\t x3\t\t Max Error (%%)\n');
fprintf('-----------------------------------------------------------------------\n');

% Iteration counter
k = 1;

while true
    % Store the old values of x
    x_old = x;
    
    % Update each component of x
    for i = 1:n
        sigma = 0;
        for j = 1:n
            if j ~= i
                sigma = sigma + A(i, j) * x(j);
            end
        end
        x(i) = (b(i) - sigma) / A(i, i);
    end
    
    % Calculate the component-wise error
    error = abs((x - x_old) ./ x);
    max_error = max(error) * 100;  % Convert to percentage
    
    % Print the current iteration, the values of x, and the max error percentage
    fprintf('%d\t\t %.6f\t %.6f\t %.6f\t %.2f%%\n', k, x(1), x(2), x(3), max_error);
    
    % Check if the maximum component-wise error is below the tolerance
    if max_error < tolerance
        break;
    end
    
    k = k + 1;
end

% Summary table
fprintf('\nSummary Table:\n');
fprintf('Iteration\t x1\t\t x2\t\t x3\t\t Max Error (%%)\n');
fprintf('-----------------------------------------------------------------------\n');
fprintf('%d\t\t %.6f\t %.6f\t %.6f\t %.2f%%\n', k, x(1), x(2), x(3), max_error);
 

Octave Online Compiler

Write, Run & Share Octave code online using OneCompiler's Octave online compiler for free. It's one of the robust, feature-rich online compilers for Octave language. Getting started with the OneCompiler's Octave editor is easy and fast. The editor shows sample boilerplate code when you choose language as Octave and start coding.