How can I stop My Gauss-Seidel loop when the if condition is met.

3 visualizaciones (últimos 30 días)
Hieu Nguyen
Hieu Nguyen el 3 de Mzo. de 2017
Editada: Bruno Luong el 30 de Sept. de 2018
D = diag(diag(A));
L = tril(-A,-1);
U = triu(-A,1);
%transition matrix and constant vector used for iterations
Tg = inv(D-L)*U;
cg = inv(D-L)*b;
tol = 1e-05;
k = 1;
x = zeros(n,1); %starting vector
N=100;
while k <= N
x(:,k+1) = Tg*(x(:,k)) + cg;
if ((norm(x(:,k+1)-x(:,k),'inf'))/(norm(x(:,k+1),'inf'))) < tol
break;
end;
k = k+1;
end;
disp(['Iteration ' num2str(k)]);
plot(x,'-o');
end
Hello, I tried to stop my iteration when ever my condition is met: infinity norm of (x(k+1) - x(k)) / infinity norm of(x(k)) < tol. Somehow, my loop will keep working until it reaches the end of my designated N. Please help me fix my while loop. Thank you.
  2 comentarios
Darshan Ramakant Bhat
Darshan Ramakant Bhat el 6 de Mzo. de 2017
Can you please put the complete code. Lots of values are missing, cannot run this script in the MATLAB editor. Also put sample test matrix 'A' in which you are getting the error. Without the data it is hard to debug.
Regards
Darshan
Bruno Luong
Bruno Luong el 30 de Sept. de 2018
Editada: Bruno Luong el 30 de Sept. de 2018
May be it's a slow convergence and you need more iterations.
My suggestion: display
norm(x(:,k+1)-x(:,k),'inf')
and
norm(x(:,k+1),'inf')
along the iterations and see how they evolve.

Iniciar sesión para comentar.

Respuestas (1)

Jan
Jan el 6 de Mzo. de 2017
The INF-norm is not sufficient here:
if ((norm(x(:,k+1)-x(:,k),'inf'))/(norm(x(:,k+1),'inf'))) < tol
What about:
if max(abs(x(:,k+1) - x(:,k)) ./ abs(x(:,k+1))) < tol
  2 comentarios
Leah Youngquist
Leah Youngquist el 29 de Sept. de 2018
Can I ask why the infinity norm is 'insufficient' here? Your solution was exactly what I needed for my problem, but I'm not sure I understand why! ((sorry if this kind of thing is against the Matlab forum rules, I'm a fresh coding baby ha-ha!))
Bruno Luong
Bruno Luong el 30 de Sept. de 2018
Editada: Bruno Luong el 30 de Sept. de 2018
Agree: Jan's expression compute exactly the same than Nguyen's expression.

Iniciar sesión para comentar.

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by