Creating dates tables with loop

조회 수: 2 (최근 30일)
Juan Manuel Romero
Juan Manuel Romero 2019년 7월 12일
댓글: Juan Manuel Romero 2019년 7월 15일
I am trying to build a matrix that contains dates separated by a time step. It woks well for the first two lines, but then it is missing a second. This is the answer i get
['16.04.2014 00:00:00'
'16.04.2014 01:00:00'
'16.04.2014 01:59:59'
'16.04.2014 02:59:59'
'16.04.2014 03:59:59'
'16.04.2014 04:59:59'
...]
It is happening only when I defined the time step as 1. Does anyone knos how can I make it work correctly?
dates(1,1)=datenum('16.04.2014 00:00:00', 'dd.mm.yyyy HH:MM:SS');
df=datenum('07.06.2016 23:59:59', 'dd.mm.yyyy HH:MM:SS'); %Final date
ddate=1; %specify time step in hours
for i=2:(df-dates(1))*24/ddate+1
dates(i,1)=dates(i-1,1)+(ddate/24);
end
%dates(end,2)=df;
dates=datetime(dates,'ConvertFrom','datenum', 'Format', 'dd.MM.yyyy HH:mm:ss');
  댓글 수: 2
dpb
dpb 2019년 7월 12일
편집: dpb 2019년 7월 12일
for i=2:(df-dates(1))*24/ddate+1
dates(i,1)=dates(i-1,1)+(ddate/24);
end
You're introduced floating point rounding error by the division in a couble and the loop. "Don't do that!"
Also you're using the deprecated datenum to generate datetime -- don't do that, either! Just use datetime from the git-go...
But, your biggest problem is that you have shortened the time span by that second you lost by setting start at 00:00:00 of one day but ending at 23:59:59 of another day but making that time difference the differential instead of incrementing by an even hour.
You can't have 23:59:59 as your end value unless you have a 59 minute, 59 second hour at the end instead of a full hour or your average day is short by the one second spread over the number of hours from beginning to end.
Juan Manuel Romero
Juan Manuel Romero 2019년 7월 15일
Thank you very much for your answer.
I don't have much experience in programming, how can then I avoid the floating point rounding error?
Also, if a need the dates as numbers in order to be able to add hours, how could I avoid using datenum?
I worked it that way because I need to get exactly the last moment of that day as the last data point in the matrix and havind the next day at 00:00:00 would add a new row that I dn't really need.

댓글을 달려면 로그인하십시오.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 7월 15일
dates = (datetime(2014,4,16,0,0,0):hours(1):datetime(2016,6,8,0,0,0))';
  댓글 수: 1
Juan Manuel Romero
Juan Manuel Romero 2019년 7월 15일
Works very well, thank you very much for the answer!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by