Grouping minute data by day and assigning to a variable
1 view (last 30 days)
Show older comments
Hey guys, I have an electricity load data in the following format

and I would like to group them by each day, so that I would have the data in the following format

I was trying to use a while loop, but I am pretty bad at coding.. Is there anyone that could help me out with this issue?
Thanks in advance.
0 Comments
Answers (1)
DGM
on 22 Dec 2021
Edited: DGM
on 22 Dec 2021
I never really do much with datetime objects, so I'm sure that there are better ways. This is at least a start. This should group the data by day. Note that this does not guarantee that the minutewise samples line up. In this example, two of the days are partial. How such a case is handled (e.g. padding) is up to you.
t1 = datetime(2020,11,1,8,0,0);
t2 = datetime(2020,11,3,8,0,0);
t = (t1:minutes(60):t2).';
data = (1:numel(t)).';
[ty tm td] = ymd(t);
tymd = [ty tm td];
tymdu = unique(tymd,'rows')
ndays = size(tymdu,1);
outdata = cell(ndays,1);
for d = 1:ndays
mask = all(tymdu(d,:) == tymd,2);
outdata{d} = data(mask).';
end
celldisp(outdata)
Using the cell array is necessary since there's no guarantee that the sample vectors are the same size. If padding is performed, then a regular array can be used instead:
t1 = datetime(2020,11,1,8,0,0);
t2 = datetime(2020,11,3,8,0,0);
t = (t1:minutes(60):t2).';
data = (1:numel(t)).';
[ty tm td] = ymd(t);
tymd = [ty tm td];
tymdu = unique(tymd,'rows'); % unique days
[th tmn ts] = hms(t);
thms = [th tmn ts];
thmsu = unique(thms,'rows'); % unique sample times
ndays = size(tymdu,1);
nsampperday = size(thmsu,1);
outdata = NaN(ndays,nsampperday);
for d = 1:ndays
daymask = all(tymdu(d,:) == tymd,2);
samplemask = ismember(thmsu,thms(daymask,:),'rows');
outdata(d,samplemask) = data(daymask);
end
outdata
daylabels = datestr([tymdu zeros(size(tymdu))],'yyyy-mm-dd')
sampletimelabels = datestr([[2000 1 1].*ones(size(thmsu)) thmsu],'HH:MM:SS')
0 Comments
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!