0

I have a datetime column matrix in MATLAB which I want to split up into separate years and assign each year to a variable. i.e if,

    Rows 1 to 5000 = 2015,

    Rows 5000 to 10000 = 2016,

    Rows 10001 to 16000 = 2017.

Can someone help me with some code to do this so I don't have to do it manually.

Thanks.

  • 3
    1) you do **not** want to assign multiple variables, because using dynamic variables is bad. Furthermore, take a look at `datevec` whose first column contains the year. You can split based on that using `unique`. – Adriaan Oct 22 '15 at 10:22
  • 1
    if you do [y,m,d] = ymd(t) where t is your datetime array, you can then index your y , m and d respectively (since they are integer representations of the date in the Matrix format). you could do year2015 = y(1:5000); or year2015 = find(y == 2015) etc. – GameOfThrows Oct 22 '15 at 10:34

2 Answers2

5

You can try doing the following. Here the vector unique_years contains the years in your datetime vector and newdatemat is a cell array with one row for every group of dates associated with a given year.

%// Sample data
datemat=[datetime(2015,5,3);...
         datetime(2015,3,5);...
         datetime(2016,4,2);...
         datetime(2014,1,1);...
         datetime(2014,3,2);...
         datetime(2017,3,3)];

%// Get the unique years from the date vector
unique_years = unique(year(datemat));

%// create a cell array newdatemat that contains
%// the datenums from datemat grouped by year
newdatemat=cell(length(unique_years), 1);
for ii=1:length(unique_years)
    newdatemat{ii} = datemat(year(datemat) == unique_years(ii));
end

An analogous version of the code above is provided below, following the suggestion of @Adriaan:

mydatevec = datevec(datemat);
unique_years = unique(mydatevec(:,1));
newdatemat1=cell(length(unique_years), 1);
for ii=1:length(unique_years)
    newdatemat1{ii} = mydatevec(mydatevec(:,1) == unique_years(ii),:);
end
houtanb
  • 3,852
  • 20
  • 21
  • Smart solution! Kudos for not using dynamic variables as per the OPs request. If you use a suggestion of mine, might I suggest [not using `i` as a variable](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab)? – Adriaan Oct 22 '15 at 11:03
  • 1
    Thanks for the suggestion @Adriaan. I updated the post accordingly – houtanb Oct 22 '15 at 11:07
2

You can use accumarray for this if you first convert it to a datenum. You can always convert back afterwards:

[~,~,subs] = unique(year(datemat));
A=accumarray(subs, datemat, [], @(x){x})

cellfun(@(x)datetime(datevec(x)),A,'uni',0)
Dan
  • 45,079
  • 17
  • 88
  • 157