How can I count all occurances of each date in a DateTime Array?
18 views (last 30 days)
Show older comments
Joshua Stephen
on 14 Sep 2020
Commented: Joshua Stephen
on 14 Sep 2020
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 Comments
Stephen23
on 14 Sep 2020
"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
on 14 Sep 2020
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'});
Accepted Answer
Cris LaPierre
on 14 Sep 2020
Edited: Cris LaPierre
on 14 Sep 2020
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
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!