You are on page 1of 3

%% Jacobi's Iterative Method

function Jacobi_Method()

%This function uses Jacobi's iterative method to solve the variable in a

%system of equations

%% -----INPUT-----

%Input A-matrix (square)

A = [ ];

%Input corresponding b-matrix (column)

b = [];

%Specify number of iterations to run

itr = 15;

%Unless otherwise specified, the intitial guess x_0 will be all zeros

x0 = zeros(1,length(A));

%% -----SOLUTION-----

n = length(A);

%To keep track of the results, we define a matrix (x) as

x = [x0;zeros(itr,n)];

%The iterative method below will run for the specified number of iteration

%above, calculate, and tabulate the values of x^k.

for k = 1:itr

for i = 1:n

%We define a variable "sigma" that will be used to sum the values
%that are known (not on the main diagonal of the matrix) for each

%row of the A-matrix (performing the calculations for each

%equation)

sigma = 0;

for j = 1:n

%Because the coefficient along the main diagonal is paired with

%the x_i we are solving for, it is omitted from the sum

if i~=j

sigma = sigma + A(i,j)*x(k,j);

end

end

%Lastly, the x_i is calculated from the equation and recorded under

%its respective iteration

x(k+1,i) = (b(i)-sigma)/A(i,i);

end

end

%% -----OUTPUT-----

%Output created for 3x3 A-matrix

%For output purposes, 'k' will be defined to show the iteration number
k = [0:itr]';

fprintf('\nSolution of the system is : \nx_1 =%9.5f \nx_2 =%9.5f \nx_3 =%9.5f \n', x(end,:))

table(k,x(:,1),x(:,2),x(:,3),...

'VariableNames',{'k','x_1','x_2','x_3'})

figure(1); hold on

plot(k,x(:,1),k,x(:,2),k,x(:,3))

legend('x_1','x_2','x_3')

title('"x" Value Trends Over Iterations "k"')

xlabel('k')

ylabel('x')

hold of

You might also like