Sum s> = 0 constraint in Matlab
I want to calculate the cumulative sum of a vector, but I stop summing as soon as the sum becomes negative and start again with positive elements.
Example:
We have a vector:
[1 1 -1 -1 -1 -1 1 1 1 1]
Then the normal total will be:
[1 2 1 0 -1 -2 -1 0 1 2]
But I want:
[1 2 1 0 0 0 1 2 3 4]
The only solution I could come across was to iterate over the elements of the vector like this:
test = [1 1 -1 -1 -1 -1 1 1 1 1];
testCumsum = zeros(size(test));
for i=1:length(test)
if i==1
testCumsum(i) = test(i);
else
testCumsum(i) = testCumsum(i-1) + test(i);
end
if testCumsum(i)<0
testCumsum(i) = 0;
end
end
Is there a more matab-ish solution?
(the sum can become negative any number of times, vectors can get quite large, and elements can be any number, not just 1 and -1)
You won't be able to vectorize it, as you need to define each element based on the previous ones. You can find areas of positive and negative runs, but that would be unnecessarily complicated and I don't know if you can follow your solution.
Here's a simplification of your code for input A
and output C
:
C=A;
C(1) = max(C(1), 0);
for k=2:numel(C)
C(k) = max(C(k-1)+C(k), 0);
end
call your vector x, y=x >0 z=x.*y sum(z)
the vector y is 0/1 where the elements of x are greater than 0, the dot product to get z sets your negative values to 0 and then you can sum
_Ah I can see more clearly what you want to do now - the loop will probably be the fastest, you can split the block segments if the array is large and use parfor to speed it up.