【问题标题】:MATLAB: Sum rows into events per minuteMATLAB:将行汇总为每分钟的事件
【发布时间】:2017-09-10 18:59:59
【问题描述】:

在 MATLAB (R2015b) 中,我有来自大型时间序列的单元格数据:

'01-Jan-2017 09:01:48'    [ 5]
'01-Jan-2017 09:01:50'    [ 2]
'01-Jan-2017 09:01:51'    [12]
'01-Jan-2017 09:01:53'    [ 2]
'01-Jan-2017 09:01:56'    [ 1]
'01-Jan-2017 09:02:00'    [ 1]
'01-Jan-2017 09:02:01'    [ 2]
'01-Jan-2017 09:02:12'    [ 1]
'01-Jan-2017 09:02:17'    [ 2]
'01-Jan-2017 09:02:19'    [ 1]
'01-Jan-2017 09:02:21'    [ 4]
'01-Jan-2017 09:02:52'    [ 1]
'01-Jan-2017 09:03:00'    [ 1]
'01-Jan-2017 09:03:05'    [ 3]
'01-Jan-2017 09:03:23'    [ 2]
'01-Jan-2017 09:03:26'    [ 3]
'01-Jan-2017 09:03:36'    [ 3]
'01-Jan-2017 09:03:37'    [ 2]
'01-Jan-2017 09:03:38'    [ 1]
'01-Jan-2017 09:03:43'    [ 2]
'01-Jan-2017 09:03:49'    [ 2]
'01-Jan-2017 09:03:51'    [ 1]
'01-Jan-2017 09:03:55'    [ 1]

但是,我想将这些行汇总为每分钟(而不是每秒)的事件,即

'01-Jan-2017 09:01:00'    [ 22]
'01-Jan-2017 09:02:00'    [ 12]
'01-Jan-2017 09:03:00'    [ 21]

我怎样才能为我的时间序列做到这一点?

【问题讨论】:

    标签: matlab time time-series cell-array


    【解决方案1】:

    您可以将discretizeaccumarray 结合使用来汇总同一分钟内出现的所有值。首先,我们必须将日期字符串的第一列转换为 datetime 对象,然后对第二列进行求和,我们使用 [data{:,2}] 将其转换为数值数组

    % Convert the first column to datetime objects and discretize by minute
    [inds, edges] = discretize(datetime(data(:,1)), 'minute');
    
    % Sum all values from the same minute
    sums = accumarray(inds, [data{:,2}]);
    
    % Create the output cell array of date strings and sums
    result = [cellstr(datestr(edges(1:end-1))), num2cell(sums)];
    
    %   '01-Jan-2017 09:01:00'    [22]
    %   '01-Jan-2017 09:02:00'    [12]
    %   '01-Jan-2017 09:03:00'    [21]
    

    更新

    所以它看起来不像 discretize 与 R2015b 中的 datetime 对象配合得很好,但您可以执行以下操作,我们将日期分解为其组件,删除秒数,确定唯一组并再次使用accumarray进行求和

    % Break each date into it's components
    dv = datevec(data(:,1));
    
    % Set the seconds to 0 so that only minutes are considered
    dv(:,end) = 0;
    
    % Find the unique minutes
    [vals, ~, inds] = unique(dv, 'rows');
    
    % Sum up the value for each unique minute
    sums = accumarray(inds, [data{:,2}]);
    
    % Create the output cell array
    result = [cellstr(datestr(vals)), num2cell(sums)];
    

    【讨论】:

    • 感谢您的帮助!我仍然得到“使用离散化时出错。输出参数太多。”当我在 MATLAB 中使用“帮助离散化”时,它仅将示例显示为“BINS = discretize(X,EDGES)”。我可以通过某种方式解决这个问题吗?还是我的版本 (R2015b) 太旧了?
    • 完美运行!!谢谢! (还有时间让我更新到新版本)
    猜你喜欢
    • 2018-09-04
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2020-11-17
    • 2014-02-27
    相关资源
    最近更新 更多