How to find the first date of each month in a datetime array?
조회 수: 22 (최근 30일)
이전 댓글 표시
I have a datetime array as below, and I like to find the first date of each month in the array.
d = [ '14-Jan-2018'
'19-Jan-2018'
'22-Jan-2018'
'26-Jan-2018'
'04-Feb-2018'
'25-Feb-2018'
'09-Apr-2018'
'14-Apr-2018'
'20-Apr-2018'
'10-May-2018'
'21-May-2018'
'01-Jun-2018'
'07-Jun-2018'
'11-Jun-2018'
'11-Jul-2018'
'31-Jul-2018'
'05-Sep-2018'
'07-Sep-2018'
'08-Sep-2018'
'28-Sep-2018'
'29-Sep-2018'
'29-Oct-2018'
'07-Nov-2018'
'12-Nov-2018'
'21-Nov-2018'
'21-Nov-2018'
'03-Dec-2018'
'12-Dec-2018'
'03-Jan-2019'
'04-Jan-2019']
d = datetime(d)
The desired output is as below.
['14-Jan-2018'
'04-Feb-2018'
'09-Apr-2018'
'10-May-2018'
'01-Jun-2018'
'11-Jul-2018'
'05-Sep-2018'
'29-Oct-2018'
'07-Nov-2018'
'03-Dec-2018'
'03-Jan-2019'
]
At first, it seems easy, but only few moments later I realized that it is a way harder and it takes me days on this problem without progress.
Please hlep with this, and thank you so much in advance for any help.
댓글 수: 0
채택된 답변
dpb
2021년 8월 27일
편집: dpb
2021년 8월 27일
firstDate=groupsummary(d,findgroups(year(d),month(d)),@min);
gives
>> firstDate
firstDate =
11×1 datetime array
14-Jan-2018
04-Feb-2018
09-Apr-2018
10-May-2018
01-Jun-2018
11-Jul-2018
05-Sep-2018
29-Oct-2018
07-Nov-2018
03-Dec-2018
03-Jan-2019
>>
댓글 수: 3
dpb
2021년 8월 29일
Indeed. It often takes some time to realize the right way to go at some operations in MATLAB. The use of grouping variables here is the key instead of trying to compute differences individually from component pieces which I gather is probably what you had tried...
추가 답변 (1개)
Campion Loong
2021년 8월 30일
Alternatively...
% dateshift all dates to beginning of the month, and find the indices of the first unique entry
[~,idx_first_month_date] = unique(dateshift(d,'start','month'));
% use the indices on your original datetime array
d(idx_first_month_date)
This yields the same result on your input:
ans =
11×1 datetime array
['14-Jan-2018'
'04-Feb-2018'
'09-Apr-2018'
'10-May-2018'
'01-Jun-2018'
'11-Jul-2018'
'05-Sep-2018'
'29-Oct-2018'
'07-Nov-2018'
'03-Dec-2018'
'03-Jan-2019'
]
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!