How to find the first date of each month in a datetime array?
22 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Doheon Lee
le 27 Août 2021
Réponse apportée : Campion Loong
le 30 Août 2021
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 commentaires
Réponse acceptée
dpb
le 27 Août 2021
Modifié(e) : dpb
le 27 Août 2021
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 commentaires
dpb
le 29 Août 2021
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...
Plus de réponses (1)
Campion Loong
le 30 Août 2021
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 commentaires
Voir également
Catégories
En savoir plus sur Dates and Time dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!