Reset value in cumsum matrix when reachin limit, and move the value to another matrix

10 views (last 30 days)
Hello
can someone please help me with this challenge.
matrix
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3] % B is Input Matrix
A = cumsum (B);
A = [1, 5, 8, 9, 12, 14, 15, 15, 15, 16, 21, 27, 36, 37, 40] % A is output Matrix, which cumulates values in Vector B
C = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] % B is also Output, initial with zero in all vallues.
Then i want A and C to act like this
A = [1, 0, 3, 4, 0, 2, 3, 3, 3, 4, 0, 0, 0, 1, 3] % Every time it exceds 5, the value has to be moved to C, and restart the accumulation from 0
C = [0, 5, 0, 0, 7, 0, 0, 0, 0, 0, 9, 6, 9, 0, 0]

Accepted Answer

Adam Danz
Adam Danz on 10 May 2019
Edited: Adam Danz on 13 May 2019
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.
% Example data
B = [1, 4, 3, 1, 3, 2, 1, 0, 0, 1, 5, 6, 9, 1, 3];
maxVal = 5; % <-- set the threshold here
% Take the cumulative sum and convert it so that it doesn't exceed the 'maxVal'
A = cumsum(B);
m = (0:maxVal:max(A))';
rm = (max(cumsum((A-m)>0))-1) .* maxVal; %amount to remove
% Here's your new A vector
Anew = A-rm;
% Here's your C vector
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
  5 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!