如何在一小时组中拆分有序的持续时间数组

时间:2015-04-19 18:28:20

标签: arrays matlab

我有一个持续时间(以秒为单位)的数组,我想将该数组拆分为 MATLAB 中不超过3600秒的累积持续时间组。持续时间是有序的。

Input:

             Duration(s) |   2010 1000 500 1030 80 2030 1090

With an:

                             ------------- ------------ ----

Accumulated duration (s) |       3510          3130     1090 

                             ------------- ------------ ----


                              1st group     2nd group   3rd 

Output:

            Groups index |    1    1    1    2   2  2    3

我尝试过一些脚本,但这些花了很长时间,我必须处理大量数据。

3 个答案:

答案 0 :(得分:3)

以下是使用bsxfuncumsum的矢量化方式:

durations = [2010 1000 500 1030 80 2030 1090]
stepsize = 3600;

idx = sum(bsxfun(@ge, cumsum(durations), (0:stepsize:sum(durations)).'),1)

idx =

     1     1     1     2     2     2     3

您可以获得的累计持续时间:

accDuratiation = accumarray(idx(:),durations(:),[],@sum).'

accDuratiation =

        3510        3140        1090

说明:

%// cumulative sum of all durations
csum = cumsum(durations);

%// thresholds
threshs = 0:stepsize:sum(durations);

%// comparison
comp = bsxfun(@ge, csum(:).',threshs(:)) %'

comp =

 1     1     1     1     1     1     1
 0     0     0     1     1     1     1
 0     0     0     0     0     0     1


%// get index
idx = sum(comp,1)

答案 1 :(得分:1)

这会让你走近。 。

durs = [2010 1000 500 1030 80 2030 1090];
cums = cumsum(durs);
t = 3600;

idx = zeros(size(durs));
while ~all(idx)    
    idx = idx + (cums <= t);
    cums = cums - max(cums(cums <= t));
end

然后,您可以通过简单的方式将输出转换为首选格式。 。

idx = -(idx-max(idx)-1)

答案 2 :(得分:0)

如果你没有足够的,还有另一种方法:

durations = [2010 1000 500 1030 80 2030 1090] ;
stepsize = 3600;

cs = cumsum(durations) ;
idxbeg = [1 find(sign([1 diff(mod(cs,stepsize))])==-1)] ; %// first index of each group
idxend = [idxbeg(2:end)-1 numel(d)] ;      %// last index of each group

groupDuration = [cs(idxend(1)) diff(cs(idxend))]

groupIndex = cell2mat( arrayfun(@(x,y) repmat(x,1,y), 1:numel(idxbeg) , idxend-idxbeg+1 , 'uni',0) )

groupDuration =
        3510        3140        1090
groupIndex =
     1     1     1     2     2     2     3

虽然如果你问我,我发现bsxfun解决方案更优雅