# MATLAB tolerance question

1. Apr 14, 2010

OK! I am not sure how to word this, but here goes:

Let's say I want to write a conditional like:

Code (Text):

for i = 1:100
if myVar(i) == 4
do some stuff
break
end

The problem is...myVar might not ever equal exactly 4. It might be that myVar == 4.001 and that is fine; I would like it to execute the code.

Now, I know that I could give it a range like:

Code (Text):

for i = 1:100
if myVar(i) < 4.002 && myVar(i) > 3.998
do some stuff
break
end

But is there a better way? Is there a function in MATLAB that takes my target value of 4 and my tolerance of .002 as its arguments? Or any other better ways?

Thanks!

2. Apr 14, 2010

### jamesrc

I don't see anything wrong with the way you are doing it. If you want to reduce your two conditions to one condition, you can use absolute value like this:

Code (Text):

target = 4; % whatever target you want
tol = 0.002; % whatever tolerance you want

if abs(myVar(i)-target) <= tol
.
.
.
or if you'd like to get rid of the loop and myVar is an array of values, you can do something like this:

Code (Text):
index = find(abs(myVar-target) <= tol,1)
.
.
.
so that index would return the index of the first value in the myVar array to meet your criteria - but that may have nothing to do with what you are trying to do.

Other than that, I'm not aware of a function that does what you are asking - but if it exists, its code probably looks a lot like what you've written. Hope that helped a little.