相同时间单位的值的cumsum

时间:2014-07-28 13:30:09

标签: matlab cumsum

我有以下向量:

A=[1 0 1 0 0 1 0 1 0 0];
B=[1 2 3 4 5 6 7 8 9 10];
在这种情况下,

表示时间向量,其中1s表示一个时间单位的开始。 现在我想将B中的所有值相加,这些值对应于具有3个相同长度的时间单位。 所以在这个例子中,这意味着第3,第4和第5个值以及B的第8,9和10值应该相加,因为它们的长度为3的时间单位。

B_result=[12 27];

我知道cumsum()是这个命令,但我不知道怎么说只有这些特定值取决于A的时间指数应该相加。

你可以帮帮我吗?

非常感谢

4 个答案:

答案 0 :(得分:2)

您可以cumsumaccumarrayhist一起使用{{3}}:

csa = cumsum(A); %// from begining og unit to unit indices
n = hist(csa, 1:max(csa));  %// count num of steps in each unit
B_result = accumarray( csa', B' ); %// accumulate B into different time units
B_result(n~=3) = []; %// discard all time units that do not have 3 steps

答案 1 :(得分:2)

N = 3; %// We want to detect a one followed by exactly N-1 zeros. Call that
%// sequence an "interesting part"
ind = find([A 1]); %// find ones. Append a last one to detect a possible 
%// interesting part at the end.
ind = ind(diff(ind)==N); %// index of beginning of interesting parts
cs = cumsum(B); %// accumulate values
B_result = cs(ind+N-1)-cs(ind-1); %// use index to build result

答案 2 :(得分:2)

对于更简单的模式匹配,您可以使用strfind

loc = strfind([A,1],[1 0 0 1]); %// add the 1 at the end of A and the pattern to avoid longer intervals
idx = bsxfun(@plus,loc,(0:2)'); %'// get the indices that need to be summed

result = sum(B(idx),1); %// obtain the result

答案 3 :(得分:2)

Jonas' Idea的更通用的应用程序:

A = [1 0 1 0 0 1 0 1 0 0 0 0 1];
B = [1 2 3 4 5 6 7 8 9 10 11 12];

n = 3;

result = arrayfun(@(x) sum( B(x:x+n-1) ), strfind([A,1],num2str(10^n+1)-48)) 

或使用cumsum代替sum,我不确定你真正想要的是什么:

result = arrayfun(@(x)  cumsum( B(x:x+n-1) ), ...
                       strfind( [A,1],num2str(10^n+1)-48 ) ,'uni',0) 

%optional:
result = cell2mat(result')