matlabsegmentscumsum

CUMSUM along rows in segments - MATLAB


I have data in array A = 100 X 612. I need to add cumulatively in 12 column segments 51 times and store the result in a new array B = 100 X 612. Final array B is summed cumulatively along 12 columns then continuing again using cumsum along columns 13:24 and continuing like this until the end columns 601:612. This is repeated 100 times in row sequence.

I've tried this using loops multiple times but can't get the answer - there must be a simpler way to get the solution..too dependent on loops!

inx = 1:12:612; %use and index   
for i = 1:100;
    for j = 1:612;
        for k = 1:51;
            B(i,j) = cumsum(A(i,inx(k):inx(k)+11));
        end;
    end;
end;

Solution

  • Using lightweight reshape and the necessary cumsum -

    intv = 12 %// interval or segment length
    B = reshape(cumsum(reshape(A,size(A,1),intv,[]),2),size(A))
    

    Basic idea here to reshape input array into a 3D array keeping the number of rows the same and with each row ending at intv lengths. Then, performing cumsum along rows and finally reshaping back to the size of input array.