# How can I prevent update of x(i) at each step of the loop? Essentially, this is a code for Gauss Seidel. How do I modify it to make it Jacobi iterative method?

2 views (last 30 days)
Avinash Gupta on 28 Mar 2021
Commented: Avinash Gupta on 31 Mar 2021
A = [7 3 2 1; 2 9 4 5; 1 3 13 4; 4 5 8 14 ]; % A is diagonally dominant
b = [1;2;3;4];
x = zeros(4,1);
%% Method I
% This code automatically updates the most recent value of x(i)
% So this becomes Gauss Seidel on its own
% Understanding has to be developed for it to become Jacobi method
for iter = 1:25
x(1) = (b(1)-A(1,2)*x(2)-A(1,3)*x(3)-A(1,4)*x(4))/A(1,1);
x(2) = (b(2)-A(2,1)*x(1)-A(2,3)*x(3)-A(2,4)*x(4))/A(2,2); % How do you make x(1) not take the updated value from previous step (ln 12)?
x(3) = (b(3)-A(3,1)*x(1)-A(3,2)*x(2)-A(3,4)*x(4))/A(3,3); % Similarly, how do you make x(1) and x(2) not update in this step?
x(4) = (b(4)-A(4,1)*x(1)-A(4,2)*x(2)-A(4,3)*x(3))/A(4,4); % And the same is desired for x(1), x(2), x(3) in this step
disp(['At iteration = ',num2str(iter), ' x = ', num2str(x')]);
end
Avinash Gupta on 31 Mar 2021
Thanks, Pavan. I get the idea now

Pavan Guntha on 31 Mar 2021
Hi Avinash,
You could try assigning the values stored in x into another variable y at the start of the loop and use the y values in your equations which follow. The following code illustrates this idea:
for iter = 1:25
y = x;
x(1) = (b(1)-A(1,2)*x(2)-A(1,3)*x(3)-A(1,4)*x(4))/A(1,1);
x(2) = (b(2)-A(2,1)*y(1)-A(2,3)*x(3)-A(2,4)*x(4))/A(2,2);
x(3) = (b(3)-A(3,1)*y(1)-A(3,2)*y(2)-A(3,4)*x(4))/A(3,3);
x(4) = (b(4)-A(4,1)*y(1)-A(4,2)*y(2)-A(4,3)*y(3))/A(4,4);
disp(['At iteration = ',num2str(iter), ' x = ', num2str(x')]);
end
Hope this helps!