3

私は次のベクトルを持っています:

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

この場合、A は時間ベクトルを表し、1 は 1 つの時間単位の開始を示します。今度は、同じ長さの 3 ステップの時間単位に対応する B のすべての値を合計したいと思います。したがって、この例では、B の 3 番目、4 番目、および 5 番目の値と、8 番目、9 番目、および 10 番目の値を合計する必要があることを意味します。これは、これらが長さ 3 の時間単位にあるためです。

B_result=[12 27];

cumsum() がこのためのコマンドであることは知っていますが、A の時間インデックスに応じてこれらの特定の値のみを合計する必要があると言う方法がわかりません。

手伝って頂けますか?

どうもありがとう

4

4 に答える 4

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
于 2014-07-28T13:48:07.203 に答える
2

およびcumsumと一緒に使用できます。accumarrayhist

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
于 2014-07-28T13:35:57.273 に答える
2

ジョナスのアイデアのより一般的なアプリケーション:

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')
于 2014-07-28T15:26:34.963 に答える