MATLAB Answers

Extract partial data from datetime using logics/vectorization

14 views (last 30 days)
Stefan555
Stefan555 on 18 Dec 2020
Answered: Eric Sofen on 5 Jan 2021
Say I have some datetime data:
rowMin =
20×1 datetime array
02-Nov-2020 09:00:00
03-Nov-2020 09:10:00
04-Nov-2020 09:00:00
05-Nov-2020 09:14:59
06-Nov-2020 09:59:59
09-Nov-2020 09:05:00
10-Nov-2020 09:00:00
11-Nov-2020 09:35:00
12-Nov-2020 13:15:00
13-Nov-2020 09:00:00
16-Nov-2020 09:00:00
17-Nov-2020 15:00:00
18-Nov-2020 09:35:00
19-Nov-2020 10:15:00
20-Nov-2020 14:10:00
23-Nov-2020 16:35:00
24-Nov-2020 09:00:00
25-Nov-2020 11:15:00
26-Nov-2020 09:00:00
27-Nov-2020 10:20:00
where I wish to separate different weekdays (always Monday to Friday):
DayNumber=weekday(rowMin);
and then to extract hours and minutes for, respectively, Mondays, Tuesday, ..., Fridays, for subsequent analysis.
How to do this - preferably using logics and vectorization?
My first attempt:
MondayH=zeros(length(rowMin),1); % preallocation
MondayM=zeros(length(rowMin),1); % preallocation
for ii=1:length(rowMin)
if DayNumber(ii,1)==2 % Monday
[MondayH(ii,1),MondayM(ii,1),~]=hms(rowMin(ii,1));
end
end
Bonus info: I would like to utilize dur (duration) on the resulting array so that I afterwards can identify mean HH:mm of the individual days.

Accepted Answer

Eric Sofen
Eric Sofen on 5 Jan 2021
I would extract the time components first and then deal with grouping by day of the week. It's easy to keep this all organized in a table:
d = datetime(2021,1,1) + minutes(randi([0,10000],[100,1])); % cook up some data
d = sort(d);
t = table(d);
t.dow = weekday(d);
t.hour = hour(d);
t.min = minute(d);
% Get the hours for Tuesday (use {} to get results as an array, () as a table)
t{t.dow == 3, "hour"}

More Answers (0)

Community Treasure Hunt

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

Start Hunting!