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

9/8/17 2:44 PM E:/Matlab/CL249/Jacobi - SSJ.M 1 of 2

Uploaded by

prabhav24051999
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)
18 views2 pages

9/8/17 2:44 PM E:/Matlab/CL249/Jacobi - SSJ.M 1 of 2

Uploaded by

prabhav24051999
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

9/8/17 2:44 PM E:\Matlab\CL249\Jacobi_SSJ.

m 1 of 2

function x = Jacobi_SSJ(A,b,x0,iter_max,rel_error_tol)
% Solve A * x = b system using iterative Jacobi method
% Created by Sujit Jogwar on July 9, 2017
% inputs
s_A = size(A);
N = s_A(1); % dimension of the system
if nargin < 3
disp('Initial guess not provided. Using default initial guess of unity vector');
x0 = ones(N,1);
iter_max = 100;
rel_error_tol = 1e-3;
elseif nargin < 4
iter_max = 100;
rel_error_tol = 1e-3;
elseif nargin < 5
rel_error_tol = 1e-3;
end
% Compatibility check

if s_A(1) ~= s_A(2)
disp('Matrix A is not a square matrix');
elseif s_A(1) ~= size(b,1)
disp('Matrix b dimensions not compatible with A');
elseif s_A(1) ~= size(x0,1)
disp('Matrix x0 dimensions not compatible with A');
else
% Matrix A conditioning
% check if any diagonal elements are zero which can result in NaN
for i = 1:N
if A(i,i) == 0
row_swap = false;
for j = i+1:N
if A(j,i) ~= 0
row_swap = true;
temp_A = A(j,:);
temp_b = b(j);
A(j,:) = A(i,:);
b(j) = b(i);
A(i,:) = temp_A;
b(i) = temp_b;
break;
end
end
if ~row_swap
% no non-zero element found below the diagonal, then
% search above the diagonal
for j = 1:i-1
if A(j,i) ~= 0 && A(i,j) ~= 0
temp_A = A(j,:);
temp_b = b(j);
A(j,:) = A(i,:);
b(j) = b(i);
A(i,:) = temp_A;
b(i) = temp_b;
break;
9/8/17 2:44 PM E:\Matlab\CL249\Jacobi_SSJ.m 2 of 2

end
end
end
end
end
x = zeros(N,1);
for i = 1:iter_max % run iterations
for j = 1:N % for each equation
sum = 0;
for k = 1:N
if k ~= j
sum = sum + A(j,k) * x0(k);
end
end
x(j) = (b(j) - sum)/A(j,j);
end
% check relative error tolerance
res = b - A*x; % residual
rel_error = norm(res)/norm(b);

if rel_error < rel_error_tol


disp(['Convergence achieved in ' num2str(i) ' iterations']);
break; % stops iterations
else
% check if max iterations have reached
if i == iter_max
disp('Maximum iterations reached without satisfying convergence
criteria');
else
% proceed to the next iteration with updated initial
% condition
x0 = x;
end
end
end
end

You might also like