MATLAB Is there a function in MATLAB for executing code with a tolerance value?

  • Thread starter Thread starter Saladsamurai
  • Start date Start date
  • Tags Tags
    Matlab Tolerance
AI Thread Summary
The discussion centers on how to handle conditional checks in MATLAB when a variable may not exactly match a target value but can be within a specified tolerance. The initial approach involves using a loop with a conditional statement to check if the variable equals 4 or falls within a range. A more efficient method suggested is to use the absolute value function to simplify the condition into a single statement that checks if the difference between the variable and the target is within the tolerance. Additionally, an alternative approach is proposed that eliminates the loop by using the `find` function to locate the first index in the array where the condition is met. No specific built-in MATLAB function for this exact scenario is identified, but the proposed methods effectively address the problem.
Saladsamurai
Messages
3,009
Reaction score
7
OK! I am not sure how to word this, but here goes:

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

Code:
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:
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!
 
Physics news on Phys.org
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:
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:
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.
 

Similar threads

Back
Top