Code covered by the BSD License  

Highlights from
modified cumsum for partial accumulated sums

modified cumsum for partial accumulated sums

by

 

Determine the accumulated sum of series of non-zero values of vectors, resetting at zero entries

cumsum_restart0( varargin )
function varargout = cumsum_restart0( varargin )
%modified version of cumsum, where the accumulated sum gets reset to zero for zero entries.
%
%[val, ind] = cumsum_restart0( arr, dim )
%if dim is not defined, use first non-singleton dimension
%val is the cumulative sum, where the accumulation is reset for zero
%entries
%ind indicates the locations where the acummulated sum is stored
%
%example: 
%arr = [3 1 1 0 1 2]';
%[val, ind] = cum_sum_restart0( arr );
%val = [0 0 5 0 0 3]'
%ind = [0 0 1 0 0 1]'
%
%3/20/13
%koehler.s.a@gmail.com
if nargin == 0
    debugging = true;
    varargin = {[3 1 1 0 1]'};
else
    debugging = false;
end
arr = varargin{1};
if numel( varargin ) > 1 
    dim = varargin{2};
    arr = shiftdim( arr, dim-1 );
else
    [arr, dim ] = shiftdim( arr );
end

%%
arr(end+1,:,:) = 0;
sz = [size(arr), 1, 1];
arr = reshape( arr, [], 1);
b = cumsum( arr, 1 );
ind = [ arr(1:end-1,:,:)>0 & ~arr(2:end,:,:); arr(end,:,:)>0];
b(~ind) = 0;
c = b(ind);
b(ind) = [c(1,:); diff( c )];
val = reshape( b, [], sz(2), sz(3) );
val(end,:,:) = [];
val = shiftdim( val, ndims(val) - dim );
if debugging
    disp( '[arr  val]' );
    disp( [varargin{1}, val] )
end
    
varargout = { val, ind };
varargout = varargout(1:nargout );

Contact us