Vector of dates going back one rolling year
이전 댓글 표시
I need to generate a rolling 1 year list of dates. I've tried using:
A=datevec(now);
DList=datenum(A(1), A(2):-1:A(2)-12, eomday(A(1), A(2)));
which will make the list I want as long as the current month is December, however it currently is not. So I get a list that goes back from November 2015 and then has multiple entries for Jan 2015 as it doesn't roll back to 2014.
Is there a straight forward way to get what I need? I don't have access to the financial toolbox so any of the functions included in it are out for me.
Thanks, Ben
채택된 답변
추가 답변 (2개)
Peter Perkins
2015년 11월 23일
If you're using a recent version of MATLAB, try using datetime:
>> dateshift(datetime('today'),'end','month',-11:0)
ans =
Columns 1 through 9
31-Dec-2014 31-Jan-2015 28-Feb-2015 31-Mar-2015 30-Apr-2015 31-May-2015 30-Jun-2015 31-Jul-2015 31-Aug-2015
Columns 10 through 12
30-Sep-2015 31-Oct-2015 30-Nov-2015
If need be, you can convertvert back to datenums afterwards.
댓글 수: 2
Ben Anderson
2015년 11월 23일
Peter Perkins
2015년 11월 23일
"Month values are an exception. MATLAB sets month values less than 1 to 1."
You could use addtodate in a loop, but see if this works for you:
>> A = datevec(now);
>> months = A(2):-1:A(2)-12;
>> years = A(1) - (months < 1)
years =
2015 2015 2015 2015 2015 2015 2015 2015 2015 2015 2015 2014 2014
>> months = months + 12*(months < 1)
months =
11 10 9 8 7 6 5 4 3 2 1 12 11
>> DList = datenum(years, months, eomday(years,months));
>> datestr(DList)
ans =
30-Nov-2015
31-Oct-2015
30-Sep-2015
31-Aug-2015
31-Jul-2015
30-Jun-2015
31-May-2015
30-Apr-2015
31-Mar-2015
28-Feb-2015
31-Jan-2015
31-Dec-2014
30-Nov-2014
A = datevec(now);
m = A(2) - [0:11];
y = repmat(A(1), 1, 12);
Find month that are in the previous years and set month and year accordingly:
idx = m < 1;
y = y - double(idx);
m(idx) = m(idx) + 12;
for i=1:12, DList(i) = datenum(y(i), m(i), eomday(y(i), m(i))); end
카테고리
도움말 센터 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!