Borrar filtros
Borrar filtros

Whike loop does not work and there is not error message

1 visualización (últimos 30 días)
MichaelO
MichaelO el 7 de Ag. de 2018
Comentada: MichaelO el 7 de Ag. de 2018
I am trying to do a loop until the last value and the value before the last one are equals. I run the code without the while (manually) and does work alright but when I run with while doesn't work. In this case the convergence is in 11 but if I change the data could be in 100 or maybe more.
If you can help me I would really appreciate. Thanks in advance.
P = [0.5,0.3,0.2;0.3,0.3,0.4;0.1,0.5,0.4];
pi=2;
py=P(pi,:);
TM=[]
kk=1
pky_new=py*P^kk
pky=[0 0 0]
while (pky_new(1,1)-pky(1,1))<0.000001
kk=kk+1;
pky=pky_new;
pky_new=py*P^kk;
TM=[TM;pky_new]
end
disp(['converge at y + ' num2str(kk)])
  2 comentarios
jonas
jonas el 7 de Ag. de 2018
Editada: jonas el 7 de Ag. de 2018
The condition is never met.
(pky_new(1,1)-pky(1,1))
ans =
0.2800
kk =
1
Perhaps it should say larger than (>)?
MichaelO
MichaelO el 7 de Ag. de 2018
Oh!!!! You are right. Thank you very much. I loose about 4 hours and I didn't realize.
Thanks again!

Iniciar sesión para comentar.

Respuesta aceptada

Rik
Rik el 7 de Ag. de 2018
You switched the condition: it is false on the first iteration and true when your loop should exit, which is the reverse from what it should be.
Also, in general you want a difference, so you should use abs. I don't understand the true goal of your code, so I don't know if that is what you should do.
P = [0.5,0.3,0.2;0.3,0.3,0.4;0.1,0.5,0.4];
pi=2;
py=P(pi,:);
TM=[];
kk=1;
pky_new=py*P^kk;
pky=[0 0 0];
while (pky_new(1,1)-pky(1,1))>0.000001% or maybe while abs(pky_new(1,1)-pky(1,1))>0.000001
kk=kk+1;
pky=pky_new;
pky_new=py*P^kk;
TM=[TM;pky_new];
end
disp(['converge at y + ' num2str(kk)])

Más respuestas (0)

Categorías

Más información sobre Startup and Shutdown en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by