Not showing the number of iterations in the output

Hey i had this project to write a matlab program that solves a problem using jacobi method.i was given a linear equation to solve. here is my program
function hw6
clear;clc;
n=3;
Jac=zeros(n); fv=zeros(n,1); f=zeros(n,1);
x=[0;0;0];
itr_max=100; tol=10^-4;
for k=1:itr_max
Jac=J(x);
fv=fx(x);
f=-1.*fv';
d=Jac\f;
x=x+d;
Rerr=abs(d./x);
fprintf('x1=%f Rerr1=%f x2=%f Rerr2=%f x3=%f Rerr3=%f\n',x(1),Rerr(1),x(2),Rerr(2),x(3),Rerr(3))
max_err=max(Rerr);
if max_err<tol;
break;
end;
end
if k==itr_max
fprintf('Newtons method failed to converge in %d iterations\n',itr_max)
if 1i<itr_max
fprintf('The solution is x(1)=%f x(2)=%f and x(3)=%f in %d iterations\n',x,k)
end
end
function Jac=J(~)
Jac(1,1)=4; Jac(1,2)=-2; Jac(1,3)=1;
Jac(2,1)=2; Jac(2,2)=5; Jac(2,3)=-2;
Jac(3,1)=1; Jac(3,2)=-1; Jac(3,3)=-3;
end
function fv=fx(x)
fv(1)=4*x(1)-2*x(2)+x(3)-3;
fv(2)=2*x(1)+5*x(2)-2*x(3)-2;
fv(3)=x(1)-x(2)-3*x(3)-0.1;
end
end
it was suppose to show the number of iterations in the output but apparently it didnt show it. please what am i doing wrong.

Respuestas (1)

dpb
dpb el 14 de Mzo. de 2015
Editada: dpb el 14 de Mzo. de 2015
The second fprintf statement is nested inside the first if...end test on the loop having completed the maximum number of allowed iterations; hence nothing will print if the algorithm succeeds in fewer.
Rewrite the if logic to account for that...one option w/ minimal changing of your code could be
if k>=itr_max
fprintf('Newton's method failed to converge in %d iterations\n',itr_max)
else
fprintf('The solution is x(1)=%f x(2)=%f and x(3)=%f in %d iterations\n',x,k)
end
The above suffers from one logic flaw, however, can you spot it? Hint: it's at the end boundary condition...

Categorías

Más información sobre Computational Fluid Dynamics (CFD) en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 14 de Mzo. de 2015

Editada:

dpb
el 14 de Mzo. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by