Reputation: 5579
I have a time vector containing time expressed in 'dd/mm/yyy HH:MM:ss'
time = { '09/01/2012 23:57:00';
'11/01/2012 01:36:00';
'12/01/2012 00:48:00';
'13/01/2012 00:35:00';}
representing the time at which I go to bed.
I would like compute the mean of the elements in the time vector to know what time I go to bed in average.
If I run
datestr(mean(datenum(time,'dd/mm/yyyy HH:MM:ss')),'HH:MM:ss')
I get
ans =
12:44:00
that is wrong (for my goal, not matematically) since Matlab makes some mess between the first and second day...indeed they are not consecutive as the others..
How to fix this?
Upvotes: 1
Views: 149
Reputation: 45752
But you haven't told Matlab that it is 01:00 the next day, you can't expect it to just assume that. In fact you are actually using date strings and not time strings. Matlab, for whatever reason, has decided that your dates are on the 1st of Jan 2015. To see this try:
time = {'01:00:00';
'22:00:00'};
datestr(datenum(times));
I don't know why it picked the 1st of Jan 2015, but it does make sense that it consistently picked the same date for both times instead of somehow reading your mind and choosing the 01:00 to be the next day.
If you want to get it right then you need to include date information as well. Picking any arbitrary date as a base:
time = {'02-Jan-2015 01:00:00';
'01-Jan-2015 22:00:00'}
Now your code should give you the time you wanted:
datestr(mean(datenum(time)),'HH:MM:ss')
Note if you wanted to automate this, you could say assume that any times before say 04:00 are the next day and then just add one day to those elements (after datenum
of course)
Based on your edit:
time = {'09/01/2012 23:57:00';
'11/01/2012 01:36:00';
'12/01/2012 00:48:00';
'13/01/2012 00:35:00';}
hours = str2num(datestr(time, 'HH')); %// Extract just the hour from the datetime
t = datenum(datestr(time, 'HH:MM:ss')); %// Extract just the time (i.e. make everything on the same day
t = t+(hours<5); %// Add one day to everything after midnight. 5 is an assumption, you can tweak this cut-off time.
datestr(mean(t),'HH:MM:ss')
ans =
00:44:00
By the way, you might want to check out the new datetime
data type. I haven't used it myself yet but just as an example, getting the hour of the time out would be a lot simpler (well, less hacky) and I'm sure there are plenty of other benefits too. Here is my attempt:
dates = datetime(time); %// using your time cell array of strings still
%// Now we must make them all the same arbitrary day:
dates.Day = 1;
dates.Year = 2015; %// or 0 or datetime('today').Year
dates.Month = 1;
%// Now we add days to those after midnight the same as before
dates.Day = dates.Day + (dates.Hour < 5);
mean(dates) %// Or datestr(mean(dates),'HH:MM:ss')
Upvotes: 1