Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views2 pages

Labfahi 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Labfahi 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

8/13/25 10:38 AM D:\al...\solutionsofsimultonousmethod.

m 1 of 2

A = [ 2 -1 1;
1 2 -1;
1 -1 2];
b = [-1; 6; -3];

x0 = [0; 0; 0];

maxIter = 25;
tol = 1e-6;

n = length(b);
x_jacobi = x0;
x_gs = x0;

err_jacobi = [];
err_gs = [];

for k = 1:maxIter
x_new = zeros(n,1);
for i = 1:n
sum1 = 0;
for j = 1:n
if j ~= i
sum1 = sum1 + A(i,j)*x_jacobi(j);
end
end
x_new(i) = (b(i) - sum1) / A(i,i);
end
err = norm(x_new - x_jacobi);
err_jacobi(end+1) = err;
if err < tol
break;
end
x_jacobi = x_new;
end

for k = 1:maxIter
x_old = x_gs;
for i = 1:n
sum1 = 0;
sum2 = 0;
for j = 1:i-1
sum1 = sum1 + A(i,j)*x_gs(j);
end
for j = i+1:n
8/13/25 10:38 AM D:\al...\solutionsofsimultonousmethod.m 2 of 2

sum2 = sum2 + A(i,j)*x_old(j);


end
x_gs(i) = (b(i) - sum1 - sum2) / A(i,i);
end
err = norm(x_gs - x_old);
err_gs(end+1) = err;
if err < tol
break;
end
end

disp('Jacobi Solution:');
disp(x_jacobi);
disp('Gauss-Seidel Solution:');
disp(x_gs);

figure;
plot(1:length(err_jacobi), err_jacobi, '-o', 'LineWidth', 1.5); hold on;
plot(1:length(err_gs), err_gs, '-s', 'LineWidth', 1.5);
xlabel('Iteration');
ylabel('Error (norm)');
legend('Jacobi','Gauss-Seidel');
grid on;
title('Error vs Iteration');

You might also like