0% found this document useful (0 votes)
11 views

GM Lab - 7 - NM - SE14AB-BA

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

GM Lab - 7 - NM - SE14AB-BA

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

NATIONAL UNIVERSITY OF SCIENCES AND

TECHNOLOGY
School of Electrical Engineering and Computer Sciences

COURSE NAME
Numerical Methods
Lab no
7

SUBMITTED BY: Ghulam Mustafa

REGISTRATION NO: 454131

CLASS: BESE 14-A

INSTRUCTOR: Bareera Anam

DATE: 30th Oct, 2024


Lab 7: Jacobi Method

Introduction
Jacobi iterative method is an algorithm for determining the solutions of a diagonally
dominant system of linear equations.

Objectives
The purpose of this lab is to get familiar with Jacobi Method

Tools/Software Requirement
Matlab R2016a

Description
Skeleton code

tol = input('Enter the tolerance, tol: ');


m = input('Enter maximum number of iterations, m: ');

A=[4 2 3 8; 3 -5 2 -14; -2 3 8 27];


x1=[0 0 0];

k = 1;
while k <= m
err = 0;

%Implement the missing part of the code here

if err <= tol


break;
else
k = k+1;
for i = 1 : n
x1(i) = x2(i);
end
end
end

fprintf('Solution vector after %d iterations is :\n', k-1);


for i = 1 : n
fprintf(' %11.8f \n', x2(i));

end

Lab Task
Implement Jacobi’s method. Hard code the input matrix and take tolerance and no. of
iterations as input and then display solution vector.
Code:

function err = jaco()


% Predefine matrix A and vector b
A = [4 2 3; 3 -5 2; -2 3 8];
b = [1; 5; 7];
x = zeros(size(b)); % Initialize x and x_new as zero
vectors of size b
x_new = zeros(size(b));
n = length(b);

% Input tolerance and max iterations


tol = input('Enter tolerance (recommended 0.001): ');
max_iter = input('Enter the max number of iterations: ');

for k = 1:max_iter
err = 0; % Reset error at each iteration
for i = 1:n
% Calculate the summation for j ≠ i
sum = A(i, [1:i-1, i+1:n]) * x([1:i-1, i+1:n]);
% Compute the new value of x
x_new(i) = (b(i) - sum) / A(i, i);
end

% Calculate the error as the infinity norm


err = norm(x_new - x, Inf);

% Check if the solution meets the tolerance


if err <= tol
fprintf('Converged after %d iterations.\n', k);
break;
end

% Update x for the next iteration


x = x_new;
end

if k == max_iter
fprintf('Max iterations reached.\n');
end
% Display solution
fprintf('Solution:\n');
disp(x);
end

Output:

Deliverables
Submit single word file with matlab code and screen shot of Output.

You might also like