[FieldTrip] bug in 'nearest' function

Tim Meehan timeehan at gmail.com
Fri Aug 4 21:00:12 CEST 2017

Dear FieldTrippers,

I'd like to report a bug in the 'nearest' function. It occurs at line 152,
the first line of the following if statement:

indx2 = find(array<=val, 1, 'last');
indx3 = find(array>=val, 1, 'first');
if abs(array(indx2)-val) <= abs(array(indx3)-val)
    indx = indx2;
    indx = indx3;
  if ~wassorted
    indx = xidx(indx);

In my case, the two values being compared should be considered equal (i.e.
val is halfway between array(indx2) and array(indx3)). However due to
precision issues, the condition is false and indx is set to indx3.

- In short format:
  val = -17.4930
  array(indx2) = -17.4940
  array(indx3) = -17.4920

- Full precision:
  val =  -17.492999999999999
  array(indx2) = -17.494000000000000
  array(indx3) = -17.492000000000001

For me this leads to the 'begsampl' variable in line 223 of
ft_timelockanalysis to be 2 when it should be 1, which then leads to an
undersizing of subsequent variables, and finally an 'index exceeds matrix
dimension' error at line 280.

I gather the precision issue was noted as a general problem a long time
ago, and the if statement noted above was implemented as a fix for the
'nearest' function -- interestingly, the fix even notes that the choice of
indx2 over indx3 when the condition is true is arbitrary (
http://bugzilla.fcdonders.nl/show_bug.cgi?id=1943). But it seems that when
val *should be* equidistant from its nearest neighbors in array, precision
issues could cause an inequality in the differences, and thus cause
'nearest' to randomly select the lesser or greater of the neighbors. I
guess it just so happens in my case that I need 'nearest' to arbitrarily
select indx2, which it is designed to to do but fails because of the
precision issue.

I did try the old (commented out) fix for precision in 'nearest' and it
solved my problem, i.e. it selects the lesser of the two neighbors. The bug
report notes this is a slower method, but I will revert to that unless it
has been found to cause other problems.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.science.ru.nl/pipermail/fieldtrip/attachments/20170804/41e0fa2e/attachment-0001.html>

More information about the fieldtrip mailing list