How can I count all occurances of each date in a DateTime Array?

25 次查看(过去 30 天)
I have an array of dates formatted in DateTime, spanning over ~2 years. Is there any way for me to tally the number of occurances each date has? I have truncated the values to only have the date portion and the datetime is formatted DD-MMM-YYYY.
  4 个评论
Stephen23
Stephen23 2020-9-14
"Yeilds a 1x78 double - not sure where I'm going wrong."
According to the histcounts documentation, when it is called with only one input argument it defines the bin boundaries using an "...an automatic binning algorithm that returns bins with a uniform width...". Your guess is as good as mine on what that would mean for your data.
In practice you will have to explicitly specify the bin boundaries or the number of bins. Whichever approach you choose, I strongly recommend that you also check its second output edges to make sure that these suit your data.
Adam Danz
Adam Danz 2020-9-14
Remove the hours:min:sec from your datetime values using t2 = dateshift(t,'start','day').
Get the unique dates using u=unique(dt).
Use the unique dates as your bins and add 1 to the final date to avoid binning problems described by Stephen.
c = histcounts(dt, [u, max(u)+1])
Now you can summarize that into a table using table(u(:),c(:),'VariableNames',{'Date','count'});

请先登录,再进行评论。

采纳的回答

Cris LaPierre
Cris LaPierre 2020-9-14
编辑:Cris LaPierre 2020-9-14
I would look into groupsummary. Like Adam suggests, you'll need to remove the time portion for it to work as you intend.
% Simple example
% create an array of overlapping dates
d = datetime('now');
dur = days(randi(10,[50 1])); % random, so results will vary
d = d+dur;
% remove time
t2 = dateshift(d,'start','day')
% Get groupcounts from table
c = groupsummary(table(t2),1)
c =
t2 GroupCount
___________ __________
15-Sep-2020 3
16-Sep-2020 6
17-Sep-2020 8
18-Sep-2020 5
19-Sep-2020 4
20-Sep-2020 4
21-Sep-2020 7
22-Sep-2020 9
23-Sep-2020 1
24-Sep-2020 3

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by