why cannot generate the sequence of Years

>> s=datetime('2014','Format','y');
ss=datetime('2019','Format','y');
t1 =s:years(1):ss;
t2= s+ years(1:5);
%
disp(t1);
disp(t2);
2014 2015 2016 2016 2017
2015 2016 2016 2017 2019

1 Comment

why t1 is not 2014 2015 2016 2017 2018 and 2019, and why t2 is not 2015 2016 2017 2018 and 2019?

Sign in to comment.

 Accepted Answer

Let's look at your vectors in a different format, with day and month information not just year information.
s=datetime('2014','Format','y');
ss=datetime('2019','Format','y');
t1 =s:years(1):ss; t1.Format = 'dd-MMM-yyyy'
t1 = 1×5 datetime array
01-Jan-2014 01-Jan-2015 01-Jan-2016 31-Dec-2016 31-Dec-2017
t2= s+ years(1:5); t2.Format = 'dd-MMM-yyyy'
t2 = 1×5 datetime array
01-Jan-2015 01-Jan-2016 31-Dec-2016 31-Dec-2017 01-Jan-2019
You want to use calendar years (which account for leap years) rather than years (which don't) as stated in the Description section of the years function.
t3 = s:calyears(1):ss; t3.Format = 'dd-MMM-yyyy'
t3 = 1×6 datetime array
01-Jan-2014 01-Jan-2015 01-Jan-2016 01-Jan-2017 01-Jan-2018 01-Jan-2019
t4 = s + calyears(1:5); t4.Format = 'dd-MMM-yyyy'
t4 = 1×5 datetime array
01-Jan-2015 01-Jan-2016 01-Jan-2017 01-Jan-2018 01-Jan-2019

More Answers (0)

Categories

Asked:

on 4 May 2023

Commented:

on 4 May 2023

Community Treasure Hunt

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

Start Hunting!