I'd like to find a vectorized way to calculate the cumulative sums of a vector, but with upper and lower limits.
In my case, the input only contains 1's and -1's. You can use this assumption in your answer. Of course, a more general solution is also welcome.
For example:
x = [1 1 1 1 -1 -1 -1 -1 -1 -1];
upper = 3;
lower = 0;
s = cumsum(x) %// Ordinary cumsum.
s =
1 2 3 4 3 2 1 0 -1 -2
y = cumsumlim(x, upper, lower) %// Cumsum with limits.
y =
1 2 3 3 2 1 0 0 0 0
^ ^
| |
upper limit lower limit
When the cumulative sum reaches the upper limit (at the 3rd element), it won't increase anymore. Likewise, when the cumulative sum reaches the lower limit (at the 7th element), it won't decrease anymore. A for-loop version would be like this:
function y = cumsumlim(x, upper, lower)
y = zeros(size(x));
y(1) = x(1);
for i = 2 : numel(x)
y(i) = y(i-1) + x(i);
y(i) = min(y(i), upper);
y(i) = max(y(i), lower);
end
end
Do you have any ideas?
cumsum
" function? – Trafficatorx
contain1's
and-1's
only? – Sarcocarpx
can contain or choose a more representativex
. Firstly have it go more than1
above and/or below the limits, have it breach the same limit more than once and most importantly as Divakar mentions, ifx
can contain other numbers please include some – Kurt