1

The following code is embedded in a function

rsp = find(response_times >= current1 & response_times < current2 & response_times ~= current2);

Here, I am looking for the indices of responses that occur between current1 and current2, where current1 and current2 are times such as 16.22 and 16.32, respectively, and the response times can be equal to current1 but not current2.

For the most part this works as intended, however, every so often it pulls an index of a value equal to current2.

Does anyone know why this might be the case or how I can improve this one line of code to fix it.

Here is an example array this code operates on:

response_times = [ 8.73000000000000
    11.4300000000000    13.4800000000000    
    14.7900000000000    16.3200000000000    
    18.0400000000000    20.3800000000000    
    20.9900000000000    21.3400000000000    
    24.2800000000000    24.6800000000000 ]; 
chappjc
  • 30,359
  • 6
  • 75
  • 132
cwdaniels
  • 71
  • 1
  • 7

1 Answers1

0

It's not actually (exactly) equal to current2. You generally shouldn't compare floating point numbers for equality. Read this article for more information, but the essence of the problem is that most values cannot be represented exactly with a floating point representation (i.e. IEEE 754), hence it is not advisable to test for equality. Inequalities are fine. There is actually a neat mini-site dedicated to providing a basic explanation of the issue.

For the Stack Overflow version of the explanation see this Q&A, entitled "Why is 24.0000 not equal to 24.0000 in MATLAB?". It's quite an interesting read!

To verify that your inequality is actually working, have it compute abs(response_times-current2) and you should find that the value is not zero in those cases, but rather something small like 1.35e-15. If you want to reject these "too close" values, include a test such as (current2-response_times)>tol and set tol to something large enough to reject these points.

Community
  • 1
  • 1
chappjc
  • 30,359
  • 6
  • 75
  • 132
  • I see. I've read up on this; however, it doesn't change the fact that I need this function to work as intended. Is there a way to tell matlab to work with decimal data? – cwdaniels Dec 06 '13 at 07:22
  • @cwdaniels Well, it is working and there is no way to change it unless you round to integers. With decimal data, you just have to set a threshold. When comparing two floats for equality, it is a common workaround to do something like `abs(f1-f2)tol` and set `tol` low enough to reject these too close points. – chappjc Dec 06 '13 at 07:29
  • I converted all my values to integers which fixed part of my problem. I realized the substantial loss of data I was experiencing was actually due to a condition statement early in the function that asked if a certain value was less than or greater than 25...it would throw out trials in which that occurred. – cwdaniels Dec 11 '13 at 06:46