我有一个时间向量,其中包含以 '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';}
代表我上床睡觉的时间。
我想计算时间向量中元素的平均值,以了解平均我几点睡觉。
如果我跑步
datestr(mean(datenum(time,'dd/mm/yyyy HH:MM:ss')),'HH:MM:ss')
我懂了
ans =
12:44:00
这是错误的(出于我的目的,不是出于交际的目的),因为Matlab在第一天和第二天之间有些混乱……事实上,它们不是连续的。
如何解决这个问题?
但是您没有告诉Matlab第二天是01:00,您不能指望它会假设这一点。实际上,您实际上是在使用日期字符串,而不是时间字符串。Matlab,无论出于何种原因,都已决定您的约会日期为2015年1月1日。要查看此尝试,请执行以下操作:
time = {'01:00:00';
'22:00:00'};
datestr(datenum(times));
我不知道为什么选择了2015年1月1日,但这确实有意义,因为它两次都选择相同的日期,而不是以某种方式阅读您的想法并将第二天的01:00选择为第二天。
如果要正确处理,则还需要包括日期信息。选择任意日期作为基准:
time = {'02-Jan-2015 01:00:00';
'01-Jan-2015 22:00:00'}
现在,您的代码应为您提供所需的时间:
datestr(mean(datenum(time)),'HH:MM:ss')
请注意,如果您想自动执行此操作,则可以假设第二天的04:00之前的任何时间都是第二天,然后只需向这些元素添加一天(datenum
当然要在此之后)
根据您的编辑:
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
顺便说一句,您可能想签出新的datetime
数据类型。我还没有亲自使用过,但是作为一个例子,花费一个小时的时间会更简单(嗯,别客气),而且我敢肯定,还有很多其他好处。这是我的尝试:
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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句