MATLAB: I am receiving an incorrect result from ADDTODATE in MATLAB 7.10 (R2010a)

addtodateerrorfloatingincrementMATLABnumberoffround

I am creating a list of time records, each of which is incremented by an hour from the previous record. At some point during the process, the record is not incremented by an hour anymore , instead by 59 mins 59.9999 seconds. So there seems to be a round off error going on. To see this behavior, download all three files, GenerateDatesHours, dateVec, and runme, execute runme.m, and see the result 'ans' in the MATLAB Variable Editor.

Best Answer

This is expected in the sense that it is caused by a roundoff error due to floating point numbers. Since each record depends on the previous one, to work around the issue, let all the records from the second record depend on the first record. Thus the following lines in GenerateDatesHours should be modified:
dates(idx+1) = addtodate(dates(idx),1,'hour'); % line 21

dates(idx) = addtodate(dates(idx-1),1,'hour'); % line 25

to
dates(idx+1) = addtodate(dates(1),idx,'hour'); % line 21
dates(idx) = addtodate(dates(1),idx-1,'hour'); % line 25