Jacobi method - I obtain the final solution, but the printed intermediary errors are wrong (zeros) ! Some intermediary steps of calculation are wrong or decayed.
1 view (last 30 days)
Show older comments
% Jacobi method for systems of equations
clc; close all; clear all
n=4; % INPUT
A=[6 2 1 2 ; 2 5 -1 1 ; 1 -1 5 -1 ; 2 1 -1 7];
b=[5 ; -16.5 ; 23.5 ; -1.5];
x0 = zeros(1,n); %intitial guess x0= all values are zero
xold=zeros(1,n);
x = [x0]';
itr=0;
err=1; errmax=0.001; itrmax=100;
while (max(err)>errmax) & (itr<itrmax)
itr=itr+1;
k(itr)=itr;
xold=x; %(itr,i)
for i = 1:n
sigma = 0; %used to sum the values for each row of the A-matrix
for j = 1:n
if j~=i %coef. from the diag. it is omitted from the sum
sigma = sigma + A(i,j)*xold(j);
end
end
x (i)= (b(i)-sigma)/A(i,i); %x_i is calc. from the eq. and recorded for each iter.
xnew(i)=x(i);
err=abs(xold-x);
%x(i)=x;
%err(i)=err;
x(itr,i)=x(i);
xold(itr,i)=xold(i);
err(itr,i)=err(i);
end
end
disp(' -----OUTPUT-----')
table(x(:,1),x(:,2),x(:,3),x(:,4),'VariableNames', {'x_1','x_2','x_3', 'x_4'})
table(xold(:,1),xold(:,2),xold(:,3),xold(:,4),'VariableNames', {'xold_1','xold_2','xold_3', 'xold_4'})
table(err(:,1),err(:,2),err(:,3),err(:,4),'VariableNames', { 'err_1','err_2','err_3', 'err_4'})
table(k(:), x(:,1),x(:,2),x(:,3),x(:,4),...
xold(:,1),xold(:,2),xold(:,3),xold(:,4), err(:,1),err(:,2),err(:,3),err(:,4),'VariableNames',...
{'k','x_1','x_2','x_3', 'x_4', 'xold_1','xold_2','xold_3', 'xold_4', 'err_1','err_2','err_3', 'err_4'})
0 Comments
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!