Clear Filters
Clear Filters

Whike loop does not work and there is not error message

1 view (last 30 days)
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 Comments
jonas
jonas on 7 Aug 2018
Edited: jonas on 7 Aug 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 on 7 Aug 2018
Oh!!!! You are right. Thank you very much. I loose about 4 hours and I didn't realize.
Thanks again!

Sign in to comment.

Accepted Answer

Rik
Rik on 7 Aug 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)])

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!