Stop Itration of a matric when it converges
Show older comments
My matrix is iterating with each element using same equation. I want to stop the iteration at convergence. My code (below) is not stopping no matter what. Can someone please help me out?
probability = (ones(1,2048) .* 1/2048);
Tij = sum(StateTransitionfwd);
Tji = sum(StateTransitionbwd);
p = ((Tji .* probability) - (Tij .* probability));
threshold = (zeros(1,2048));
old = p;
new = zeros(1,2048);
while true
p = ((p * StateTransitionbwd) - (Tij .* p));
new = p;
if old-new <= threshold
break
end
old = p;
%old - new = threshold;
end
Answers (1)
Walter Roberson
on 24 Aug 2015
Try
if abs(old-new) <= threshold
4 Comments
Salman Saeed
on 24 Aug 2015
Walter Roberson
on 24 Aug 2015
You appear to be working with vectors. When you use "if" with a vector condition, the "if" is only considered true if all of the entries in the vector are true. If that is what you want, then it is recommended that you code it specifically using all() as in
if all(abs(old-new) <= threshold)
as that way people reading the code will know that you have specifically thought about this difficulty.
If you want to stop the loop if at least one of the entries in the vector is true, then use the line as above but replace all() with any()
If you do want the execution to proceed until all() of the conditions are met, you need to analyze to see if that is even possible.
I do not follow exactly what you are doing with the subtraction in the determination of the new p, but it looks a bit odd to me that you are calculating the sum of the Forward transition matrix and mixing that with the Backwards transition matrix. Plausibly that is correct, but I would naively expect the Backwards sum Tji to be used with the Backwards Transition matrix. A comment would be good there.
Salman Saeed
on 28 Aug 2015
Salman Saeed
on 28 Aug 2015
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!