How to find the first date of each month in a datetime array?
21 次查看(过去 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!