First interpretation
I believe the OP wants to integrate over B but not allow the cumulative sum to exceed a threshold of 5. So "A" would be a vector not exceeding 5 while "C" would be a vector of 0s except for the values in "A" that were closest to 5.
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3];
maxVal = 5;
A = cumsum(B);
m = (0:maxVal:max(A))';
rm = (max(cumsum((A-m)>0))-1) .* maxVal;
Anew = A-rm;
C = zeros(size(Anew));
C(diff(Anew) < 0) = Anew(diff(Anew) < 0);
Results
Anew =
1 5 3 4 2 4 5 5 5 1 1 2 1 2 5
C =
0 5 0 4 0 0 0 0 5 0 0 2 0 0 0
Second interpretation
(as described futher by OP in the comments below).
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3];
A = cumsum (B);
C = zeros(size(A));
for i = 1:length(A)
if A(i) >= 5
C(i) = A(i);
A(i:end) = A(i:end)-A(i);
end
end
Results
A =
1 0 3 4 0 2 3 3 3 4 0 0 0 1 4
C =
0 5 0 0 7 0 0 0 0 0 9 6 9 0 0
Best Answer