且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 MATLAB 中使用时间序列按天/小时计算值

更新时间:2023-02-26 15:37:31

正如 其他 所建议的,您应该将字符串日期到序列日期数字.这使得处理数字数据变得容易.

As others have suggested, you should convert the string dates to serial date numbers. This makes it easy to work with the numeric data.

计算每个间隔(天、小时、分钟等)的事件数的一种有效方法是使用 HISTC累加器.该过程将涉及操作将序列日期转换为此类函数所需的单位/格式(例如 ACCUMARRAY 需要整数,而 HISTC 需要被赋予 bin 边缘以指定范围).

An efficient way to count number of events per interval (days, hours, minutes, etc...) is to use functions like HISTC and ACCUMARRAY. The process will involve manipulating the serial dates into units/format required by such functions (for example ACCUMARRAY requires integers, whereas HISTC needs to be given the bin edges to specify the ranges).

这是一个矢量化解决方案(无循环),它使用 ACCUMARRAY 来计算事件数.这是一个非常有效的功能(即使输入很大).一开始,我生成了一些 5000 个时间戳的样本数据,这些时间戳在 4 天的时间内不均匀分布.您显然想用自己的替换它:

Here is a vectorized solution (no-loop) that uses ACCUMARRAY to count number of events. This is a very efficient function (even of large input). In the beginning I generate some sample data of 5000 timestamps unevenly spaced over a period of 4 days. You obviously want to replace it with your own:

%# lets generate some random timestamp between two points (unevenly spaced)
%# 1000 timestamps over a period of 4 days
dStart = datenum('2000-01-01');     % inclusive
dEnd = datenum('2000-01-5');        % exclusive
t = sort(dStart + (dEnd-dStart).*rand(5000,1));
%#disp( datestr(t) )

%# shift values, by using dStart as reference point
dRange = (dEnd-dStart);
tt = t - dStart;

%# number of events by day/hour/minute
numEventsDays = accumarray(fix(tt)+1, 1, [dRange*1 1]);
numEventsHours = accumarray(fix(tt*24)+1, 1, [dRange*24 1]);
numEventsMinutes = accumarray(fix(tt*24*60)+1, 1, [dRange*24*60 1]);

%# corresponding datetime range/interval label
days = cellstr(datestr(dStart:1:dEnd-1));
hours = cellstr(datestr(dStart:1/24:dEnd-1/24));
minutes = cellstr(datestr(dStart:1/24/60:dEnd-1/24/60));

%# display results
[days num2cell(numEventsDays)]
[hours num2cell(numEventsHours)]
[minutes num2cell(numEventsMinutes)]

这是每天事件数量的输出:

Here is the output for the number of events per day:

'01-Jan-2000'    [1271]
'02-Jan-2000'    [1258]
'03-Jan-2000'    [1243]
'04-Jan-2000'    [1228]

以及每小时事件数量的摘录:

And an extract of the number of events per hour:

'02-Jan-2000 09:00:00'    [50]
'02-Jan-2000 10:00:00'    [54]
'02-Jan-2000 11:00:00'    [53]
'02-Jan-2000 12:00:00'    [74]
'02-Jan-2000 13:00:00'    [49]
'02-Jan-2000 14:00:00'    [59]

同样持续几分钟:

'03-Jan-2000 08:54:00'    [1]
'03-Jan-2000 08:55:00'    [1]
'03-Jan-2000 08:56:00'    [1]
'03-Jan-2000 08:57:00'    [0]
'03-Jan-2000 08:58:00'    [0]
'03-Jan-2000 08:59:00'    [0]
'03-Jan-2000 09:00:00'    [1]
'03-Jan-2000 09:01:00'    [2]