0

I want to iterate all of the elements in my matrix and want them to stop when the value converges of all the elements. I wrote the code (below) but its giving me wrong values and i dont think if values are actually going in the loop.

probability = (ones(1,2048) .* 1/2048); %vector of 2048 values
Tij = sum(StateTransitionfwd); %vector of 2048 values
Tji = sum(StateTransitionbwd); %vector of 2048 values
p = ((Tji .* probability) - (Tij .* probability)); %vector of 2048 values

threshold = (zeros(1,2048)); %vector of 2048 values
old = p; %vector of 2048 values
new = zeros(1,2048); %vector of 2048 values

while old - new > threshold %subtracting vector from the vector    
   old = p;     
   p = ((p * StateTransitionbwd) - (Tij .* p));     
   new = p;        
end 
Shai
  • 111,146
  • 38
  • 238
  • 371
  • I think your array will simply never converge to zero and therefore always run. Try setting the threshold higher or include a maximum number of iterations in your while-loop condition. – Adriaan Aug 24 '15 at 08:11
  • @Visser I tried doing it. values were not going into the loop first but by using norm(old - new) they are. But now I am getting values in Inf or NaN :s – Salman Saeed Aug 24 '15 at 08:47
  • Both Tij and Tji are scalars. Multiplying them with probability gives an array containing 2048 values which are exactly the same. Subtracting those two arrays again gives a 2048 element array with exactly the same entries. Only when you assign p inside the while loop things start to change, providing StateTransitionbwd is a 2048 array of distinct values. – Adriaan Aug 24 '15 at 08:50
  • The number of elements remain the same (that is 2048) but their values are in NaN or inf. – Salman Saeed Aug 24 '15 at 08:54

2 Answers2

0

You stopping condition old - new > threshold is problematic, since it is not evaluated into a scalar boolean value, but to a vector of boolean values.
You should instead measure the norm of the difference vector, for example

while max( abs( old-new) ) > threshold

Or

while norm( old-new) > threshold
Shai
  • 111,146
  • 38
  • 238
  • 371
0

It seems to me that your old vector might be the 0 vector as well. If you get an error of NaN or inf when testing the loop condition it is because you try to find the norm of the zero vector with norm(old-new). The norm of a vector is calculated by v/||v|| so if ||v|| is 0, your vector will be NaN.