How to find the first date of each month in a datetime array?

21 ビュー (過去 30 日間)
Doheon Lee
Doheon Lee 2021 年 8 月 27 日
回答済み: Campion Loong 2021 年 8 月 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.

採用された回答

dpb
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
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...
Doheon Lee
Doheon Lee 2021 年 8 月 30 日
yes, it is pretty hard to realize the right way to do. What I learned from you will solve many problems that I definitely encounter in the future. Once again, thank you so much for the help :)

サインインしてコメントする。

その他の回答 (1 件)

Campion Loong
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'
]

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by