MATLAB: Create columns with for loop

for loop

Hello,
I am trying to get the cumultive sum of a column but only between certain rows. The rows are found based on a condition and stored in an array(Rows_I_need). For example [500 1000, 2500].
I want to create the cumulitive sum of row 1-499, 500-999, 1000-2499, 2500-end. I have working code for the start and end section and have created a for-loop for the middle section. My problem is, that the for-loop creates the cumlitive sum between rows 500-999 and then takes the last value as a starting point for the next section rows 1000-2499.
Below is an image explaining the problem and my code:
Sum.PNG
Rows_I_need=find(FlowData.weightDiffAfter<-0.5); %find sections
c0=cumsum(column1(1:Rows_I_need(1)-1));%cumsum of first section
h=length(Rows_I_need);
c_last=cumsum(column1(Rows_I_need(a):length(column1))); %cumsum of last section
for a=(length(Rows_I-need)-1)
for k=Rows_I_need
c1=cumsum(column1((k:k(a+1)-1)));
end
end

Best Answer

This should help you solve it:
Rows_I_need=[500, 1000, 2500];
%generate random array as input
array=randi(3,4000,1);
%get cumsum
output=cumsum(array);
for k=1:numel(Rows_I_need)
%subtract the value before the new start-point from all subsequent
%points
one_value_up=output(Rows_I_need(k)-1);
output(Rows_I_need(k):end)=output(Rows_I_need(k):end)-one_value_up;
end