Cumulative sum between two trues in array according to positions stored in logical array

조회 수: 3 (최근 30일)
Hello!
I would like to find a fast way to get cumulative sums of values of an array according to the starting and ending positions given by a logical array,
for instance:
v=[0;1;2;0;2;4;5;6;2;3;4];
pos=[true;false;true;false;false;true;false;true;false;false;true];
I would like the code to cumulative sum vector "x" between two trues, getting the following result:
result=[3;8;15;15]; %I summed [2+1+0;4+2+0+2;6+5+4;4+3+2+6]
Hope that the question is clear, thank you!

채택된 답변

Matt J
Matt J 2022년 10월 17일
편집: Matt J 2022년 10월 17일
v=[0;1;2;0;2;4;5;6;2;3;4];
pos=[true;false;true;false;false;true;false;true;false;false;true];
cv=cumsum(v);
I=find(pos);
result = cv(I(2:end))-cv(I(1:end-1)) +v(I(1:end-1))
result = 4×1
3 8 15 15

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by