Search code examples
matlabloopserror-handlingmargins

Error margin for a value in an if statement in Matlab?


I have a simple for loop :

for n=0:0.001:100
  if x<100
    do something
  end
end

However, due to the complexity of the code, the final value of x is around 100.345, hence the loop breaks.

I want to apply an error margin where if x<100 ± 0.4 so that the statement is true and the loop restarts.

How is this possible ?


Solution

  • Use the logical and (&&) operator to make a range. The conditional code is executed only if both statements are true.

    e = 0.4;    
    v = 100;
    if x<v+e && x>v-e
        do something
    end 
    

    You can set n=0 in the conditional code to restart the loop if you like.