-
Notifications
You must be signed in to change notification settings - Fork 0
/
jacobiMethod.m
45 lines (42 loc) · 1.48 KB
/
jacobiMethod.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
% Program to solve a diagonally dominant system of linear equations using Jacobi iterative method.
% in Jacobi we use the old x instead of new one, opposite to as in Gauss-Seidel, makes it slower.
clc; clear all;
% Inputs
disp('For `Ax=B` system of equations.')
A = input('Matrix A : ');
B = input('Matrix B : ');
x0 = input('Initial guess x0 : ');
tolerance = input('Tolerance required : ');
maxIte = input('Maximum Iterations : ');
if size(B,1) ~= size(A,1) || size(x0,1) ~= size(A,1)
disp('Invalid Inputs B and/or x0, please provide as `nx1` matrix.')
else
N = size(A,1);
ite = 1;
x=zeros(size(x0));
gotSoln=false;
while ite <= maxIte
for row = 1:N
x(row) = (B(row) - A(row,1:row-1)*x0(1:row-1) - A(row,row+1:N)*x0(row+1:N)) / A(row,row);
end
if abs(x-x0) < tolerance
gotSoln=true;
fprintf('\nConverged, Solution of system is :');
x
fprintf('Iterations Required : %d\n',ite);
break;
else
ite = ite + 1;
x0 = x;
end
end
end
if ~gotSoln
disp('Did not converge.')
disp('Possible reasons include -')
disp('Matrix A is')
disp('neither `strictly or irreducibly diagonally dominant`')
disp('nor `symmetric positive-definite`; however still not guaranteed to converge if it is.')
disp('The standard convergence condition (for any iterative method) -')
disp('Spectral radius of the iteration matrix should be less than 1.')
end