what is wrong with the following code

3 views (last 30 days)
Opariuc Andrei
Opariuc Andrei on 9 Nov 2020
Edited: Opariuc Andrei on 9 Nov 2020
i'm trying to do the jacobi method for some linear equations and i'm receiving NaN as a result
%% Input data
n=input('number of ecuations, n:');
ni=input('number of iterations , ni:');
tol=input('tolerance,tol: ');
A=zeros(n,n+1);
x1=zeros(n);
x2=zeros(n);
x1=[1 1 1];
%% Ecuations
%% Ec1: x1 + 5x2 - 6x3 = 5
%% Ec2: 3x1 + x2 + 5x3 = 23
%% Ec3: x1 + 4x2 + x3 = 7
%% System Matrix
a=[1 5 -6 5;3 1 5 23 ;1 4 1 7];
%% Calculus
k=1;
while k<=ni
error=0;
for i=1:n
s=0
for j=i:n
s=s-A(i,j)*x1(j);
end
s=(s+A(1,n+1))/A(i,i);
if abs(s)>error
error=abs(s)
end
x2(i)=x1(i)+s;
end
if error<=tol
break
else
k=k+1;
for i=1:n
x1(i)=x2(i);
end
end
end
fprintf(' solution after %d iterations is :\n' ,k-1);
for i=1:n
fprintf('%11.8f\n',x2(i));
end

Answers (0)

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!