How to find the first date of each month in a datetime array?
22 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Doheon Lee
el 27 de Ag. de 2021
Respondida: Campion Loong
el 30 de Ag. de 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 comentarios
Respuesta aceptada
dpb
el 27 de Ag. de 2021
Editada: dpb
el 27 de Ag. de 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 comentarios
dpb
el 29 de Ag. de 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...
Más respuestas (1)
Campion Loong
el 30 de Ag. de 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 comentarios
Ver también
Categorías
Más información sobre Dates and Time en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!