I want to create a date vector in serial format. I know the end date, but I wish to be able to go lets say n period back from this date in either daily or weekly steps. The end date should be at the bottom of the vector. Any help?

1 view (last 30 days)
I want to create a date vector in serial format. I know the end date, e.g, 21st June 2018, but I wish to be able to go lets say 500 period back from this date in either daily or weekly steps. The end date should be at the bottom of the vector. Any help? Any functions I can use for this, with input of end date and time step?
I have attempted the following. It works, but is there a better way? A function perhaps?
enddate = datenum(2018, 6, 21, 0, 0, 0); % Next, use datenum again to define the interval of 7 days: offset = datenum(0, 0, 7, 0, 0, 0);
% Finally, make a 250-element vector by multiplying the numbers 0 through 249 by the % offset and adding them to the start date:
vec = enddate - (0:249)*offset; %You can verify the results by converting the serial date numbers in vec back to strings: Thedateseries = datestr(vec);
Thedateseriesrev = flipud(Thedateseries);
mydatesseries =cellstr(Thedateseriesrev);

Answers (1)

Steven Lord
Steven Lord on 25 Jun 2018
I recommend working with a datetime array rather than serial date numbers.
startDate = datetime('today');
period = days(3);
v = startDate + (0:7)*period
You can use negative time periods as your increment.
startDate = datetime('today');
period2 = days(-4);
v2 = startDate + (0:4)*period2
You aren't limited to just using periods of days or hours, you can combine to form finer-grained increments.
startDate = datetime('today');
period3 = days(1)+hours(6);
v3 = startDate + (0:6)*period3
differenceBetweenElements = diff(v3)
While differenceBetweenElements is correct (1 day + 6 hours = 30 hours) let's display it in the format days:hours:minutes:seconds to make it clearer that the spacing is in fact 1 day and 6 hours.
differenceBetweenElements.Format = 'dd:hh:mm:ss'

Tags

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!