Quick way to sum array elements based on flag in another array?
显示 更早的评论
Say I have 2 arrays: one with "clean" data, and one that tells me which data gets lost, as indicated by zeros. If an element is lost, it should be added to the next observed element. Anybody got a quick one-or-two-liner to come up with the summed array?
Example:
clean = [1 2 3 4 5 6]
lost = [1 0 3 0 0 6]
desired = [1 5 15]
1 个评论
Sean de Wolski
2015-7-14
Fun question, well asked with example inputs and expected outputs +1
采纳的回答
更多回答(2 个)
Andrei Bobrov
2015-7-14
编辑:Andrei Bobrov
2015-7-14
desired = flip(accumarray(cumsum(lost(end:-1:1)~=0)',clean(end:-1:1)),1)';
or
desired = accumarray(cumsum(xor([0,diff(lost > 0)],lost))',clean)';
Sean de Wolski
2015-7-14
accumarray(interp1(find(lost),1:nnz(lost),1:numel(lost),'next')',clean)
4 个评论
Ted
2015-7-14
Sean de Wolski
2015-7-14
Yes it does! Well it's transposed but the numbers are correct
clean = [40 10 50 30 40 10 50 30 40 10 50 30];
lost = [40 0 50 30 0 10 0 0 40 10 50 30];
accumarray(interp1(find(lost),1:nnz(lost),1:numel(lost),'next')',clean)
ans =
40
60
30
50
120
10
50
30
You could always transpose the answer with '
Andrei Bobrov
2015-7-14
+1
Ted
2015-7-15
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!