MATLAB Answers


Can I reference dates, instead of element index numbers, when referencing a time series?

Asked by Önundur Ragnarsson on 19 Jun 2018
Latest activity Commented on by Steven Lord
on 26 Jun 2018
Accepted Answer by KL
I would like to reference certain sub-samples from my time series, which are quarterly economic data. I have many series with differing start and finish dates, but I want to split them all into sub-samples, at the same date, before performing some operations on them.
For example:
Series X1 extends from 31.3.1975 to 31.12.2017
Series X2 extends from 30.6.1983 to 31.12.2009
I want to split them both at 31.12.2000 into:
X1old from 31.3.1975 to 31.12.2000 and X1new from 31.3.2001 to 31.12.2017
X2old from 30.6.1983 to 31.12.2000 and X2new from 31.3.2001 to 31.12.2009
Can this be done by referencing dates, rather than element index numbers in the time series vectors themselves?


Sign in to comment.

2 Answers

Answer by KL
on 19 Jun 2018
 Accepted Answer

Use the dates to extract the desired indices. Look at the following example,
% Create some dummy data
t = datetime([2018 1 1 1 1 1]):days(30):datetime([2018 6 1 1 1 1]);
X = table(t.', rand(numel(t),1))
% find indices of the elements which are before 31.3.2018
indx = X{:,1}<=datetime([2018 3 31 23 0 0]);
% the corresponding elements
% other elements

  1 Comment

Sign in to comment.

Answer by Steven Lord
on 26 Jun 2018

If you use a timetable to store your data instead of a table, you could take advantage of timerange.
% Create a timetable
times = datetime([2018 1 1 1 1 1]):days(30):datetime([2018 6 1 1 1 1]);
data = randi([-10 10], numel(times),1);
tt = timetable(times.', data)
startOfRange = datetime([2018 3 31 23 0 0]);
% Option 1
tt(tt.Time < startOfRange, :)
% Option 2, good for a finite interval
interval2 = timerange(startOfRange, startOfRange + days(60))
tt(interval2, :)
% Option 3, an infinite interval
interval3 = timerange(startOfRange, Inf)
tt(interval3, :)
Using a timetable also gives you access to retime and synchronize. These functions as well as groupsummary (which is new in release R2018a and works on both table and timetable arrays) may help you analyze your financial data. For instance, to compute the sum of the data for each month in the timetable tt created above:
tt2 = retime(tt, 'monthly', 'sum')


I am currently running on R2016b but I will definitely keep this in mind when I get an upgrade. Thank you so much!
timetable, retime, and synchronize were all introduced in release R2016b. Of the functions I listed, only groupsummary was introduced later.

Sign in to comment.