MATLAB: ‘hour’ function output and ‘datestr’ output is not matching

MATLAB: ‘hour’ function output and ‘datestr’ output is not matching

datestrhour

I often use Matlab ‘hour’ and ‘datestr’ /’datenum’ functions and it always worked fine. But recently at a specific time I found the following issue. I was using the time as 7.357206249999994e+05 for which ‘datestr’ gives correct ans but ‘hour’ didn’t match.
>>datestr(7.357206249999994e+05)
ans =
'01-May-2014 15:00:00'
K>> hour(7.357206249999994e+05)
ans =
14
As you can see the hour didnt match in the datestr output and hour output, and most likely it is happening for rounding because hour(7.357206250000000e+05) gives ans 15. But since I get these time values through codes so how to deal with this round off in date tracking. I used the following code:
>>current_tim=datenum(datestr('01-May-2014 00:00:00'));
>> for k=1:24*7
[out]=function(theta_pre,weaData,current_tim,I(k));
current_tim=current_tim+datenum(0,0,0,1,0,0) ;%adding one hour in each loop
datestr(current_tim)%checking

hour(current_tim)%checking
end

Best Answer

  • Yes, it is rounding. datenum(’01-May-2014 15:00:00′) is 735720.625 so anything that does not reach .625 after whatever internal rounding will convert to hour 14. Experimentally I find that the breakpoint is between 735720.625 * (1-35*eps) and 735720.625 * (1-36*eps) which is somewhere around 6.8E-10 seconds
    current_tim=current_tim+datenum(0,0,0,1,0,0) ;%adding one hour in each loop
    Remember that datenum(0,0,0,1,0,0) is going to be expressed in floating point as fractions of a day, not as integral hours. As 1/24 is not exactly representable in double precision floating point, the double precision representation of 1/24 is going to be either a hair less than the true 1/24 or a hair more than the true 1/24. When you start adding together those hairs, you are going to end up with values that are not exactly what they should be algebraically, leading to problems like you saw.
    Try
    start_tim=datenum(datestr('01-May-2014 00:00:00'));
    for k=1:24*7
    current_tim = start_tim + (k-1)/24; %k hours
    datestr(current_tim)%checking

    hour(current_tim)%checking
    [out] = YourFunction(theta_pre,weaData,current_tim,I(k));
    end
  • Add a Comment

    Your email address will not be published. Required fields are marked *