MATLAB: For loop adding and substracting.

arrayfor loopMATLABsimulinkwhile loop

Hello Matlab community!
Could someone please give me a hand with my code?
I've come up with an array such as
A = [0, 0, 0, 0, 0, 0, 4, 5, 6, 9, 4, 3, 9, 0, 0, -1, -1, -1, -1, 0, 0, 3, 2, 8, 3, 0, -1, 0, -1, 0, -1, -1, 0, 0, 5, ..., n]
The main idea is adding A(n) values when A(n) is 0 or positive.
But when A(n) is -1, I'd like it to subtract the sum of the previous positions into equal parts (1/4) to get zero.
(Note: there are always four -1 before a positive value, so the sum should be divided by 4). The output should be as follows:
Output = [0, 0, 0, 0, 0, 0, 4, 9, 15, 24, 28, 31, 40, 40, 40, 30, 20, 10, 0, 0, 0, 3, 5, 13, 16, 16, 12, 12, 8, 8, 4, 0, 0, 0, 5,..., n]
I hope I've explained myself clear enough for you to understand.
Thank's for the help!

Best Answer

decrA = 0;
out = zeros(1, numel(A));
out(1) = A(1);
for idx = 2:1:numel(A)
if A(idx) == -1
out(idx) = out(idx - 1) - decrA;
else
out(idx) = out(idx - 1) + A(idx);
decrA = out(idx)/4;
end
end
out
Does this solve your issue?