MATLAB: Date/time matrix for every hour.

datehourlymatrixtime

I want to to create an hourly date/time matrix starting from 2006-12-01 and ending: 2016-12-31. It must start at midnight and end at 23:00 for each day. How do I do that?

Best Answer

Without datetime class, use datenum...same idea, just a little more work
>> first = datenum(2006, 12, 1);
>> last = datenum(2017, 1, 1);
>> xt = datenum(2006, 12, 1,[0:(last-first)*24-1].',0,0);
>> datestr(xt(1))
ans =
01-Dec-2006
>> datestr(xt(end))
ans =
31-Dec-2016 23:00:00
>>
datenums are just doubles so don't have the display features of the specialized class, have to use datestr to show the calendar form.
See
doc datenum % to convert to datenums from string/numeric format
doc datestr % for output calendar formatting
doc datetick % for plot axes
for the details; more examples. Also if plotting, use the datenum as the value but have to fix up the axis display with datetick. There are some other supporting functions; see the "See Also" sections.
Since datenums are just doubles, ":" doesn't have the magical properties it has with the datetime class to use as Steven did in his answer; instead datenum has the internal "smarts" to wrap any field based on calendar time; hence the hours vector from the beginning time. It's tempting to try to do the calculation outside datenum as
dt=1/24; % one hour fraction of day
dn=datenum(start):dt:datenum(end); % generate hourly datenum series
but this is fraught with problems of floating point roundoff, always use an integer series of the proper graunularity as above to ensure comparisons will work as expected.