Whike loop does not work and there is not error message

1 次查看(过去 30 天)
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 个评论
jonas
jonas 2018-8-7
编辑:jonas 2018-8-7
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 2018-8-7
Oh!!!! You are right. Thank you very much. I loose about 4 hours and I didn't realize.
Thanks again!

请先登录,再进行评论。

采纳的回答

Rik
Rik 2018-8-7
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)])

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by