0
votes

I have created a 'for' loop in a matlab function. What I want to do is to execute the loop for a predetermined number of iterations (maxsteps), but if the difference between the most recent result F(step) and the previous result F(step-1) is bellow a specified threshold then to cut the loop short:

for steps = 1:maxsteps

  (various calculations)

 if F(steps) - F(steps-1) < 0.001
   Break
 end
end

The F(steps) is a N(=maxsteps) dimension vector which on each loop 'gets' a new column by performing a sum between two values which are different on every iteration: F(steps) = a + b.

Assuming maxsteps is 8 (or any integer) when I execute the function I get the following error:

Subscript indices must either be real positive integers or logicals.

If I execute the function without the Break then it works perfectly (but I am loosing the option of the threshold of course).

EDIT[1]: Now that I saw the problem again, I am thinking that the issue might be in the first iteration. Because when steps = 1 then F(1) - F(0) < 0.001, which I assume is impossible. I need to think of something to fix that problem.

1

1 Answers

0
votes

The issue (as you've noted) is that the first time through the loop, you are performing this operation:

F(1) - F(0) < 0.0001 

This zero-index is invalid and causing your error.

What you want to do instead is ensure that you execute the entire loop at least once (to avoid the zero index). So you can add an extra conditional to your if statement.

if steps > 1 && (F(steps) - F(steps-1)) < 0.0001

The use of the logical and (&&) will not evaluate the second conditional if the first evaluates to false.