Home > FMAToolbox > General > CumSum.m

CumSum

PURPOSE ^

CumSum - Cumulative sum of elements. Partial sums can also be computed.

SYNOPSIS ^

function s = CumSum(data,stops)

DESCRIPTION ^

CumSum - Cumulative sum of elements. Partial sums can also be computed.

  USAGE

    sum = CumSum(data,stops)

    data           data to sum
    stops          optional logical indices where sum should be restarted

  EXAMPLE

    % Simple cumulative sum
    s = CumSum([1 4 6 2 13]);

    % Partial cumulative sums
    s = CumSum([1 4 6 2 13 2 4 6 5 10 1],[1 0 0 0 0 1 0 0 0 0 0])

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function s = CumSum(data,stops)
0002 
0003 %CumSum - Cumulative sum of elements. Partial sums can also be computed.
0004 %
0005 %  USAGE
0006 %
0007 %    sum = CumSum(data,stops)
0008 %
0009 %    data           data to sum
0010 %    stops          optional logical indices where sum should be restarted
0011 %
0012 %  EXAMPLE
0013 %
0014 %    % Simple cumulative sum
0015 %    s = CumSum([1 4 6 2 13]);
0016 %
0017 %    % Partial cumulative sums
0018 %    s = CumSum([1 4 6 2 13 2 4 6 5 10 1],[1 0 0 0 0 1 0 0 0 0 0])
0019 %
0020 
0021 % Copyright (C) 2004-2011 by Michaƫl Zugaro
0022 %
0023 % This program is free software; you can redistribute it and/or modify
0024 % it under the terms of the GNU General Public License as published by
0025 % the Free Software Foundation; either version 3 of the License, or
0026 % (at your option) any later version.
0027 
0028 if nargin < 1,
0029     error('Incorrect number of parameters (type ''help <a href="matlab:help CumSum">CumSum</a>'' for details).');
0030 end
0031 if ~isvector(data),
0032     error('Parameter ''data'' is not a vector (type ''help <a href="matlab:help CumSum">CumSum</a>'' for details).');
0033 end
0034 data = data(:);
0035 if nargin == 2,
0036     if ~isvector(stops),
0037         error('Parameter ''stops'' is not a vector (type ''help <a href="matlab:help CumSum">CumSum</a>'' for details).');
0038     end
0039     stops = logical(stops(:));
0040     if length(stops) ~= length(data),
0041         error('Parameters ''data'' and ''stops'' have different lengths (type ''help <a href="matlab:help CumSum">CumSum</a>'' for details).');
0042     end
0043 end
0044 
0045 % Simple cumulative sum
0046 s = cumsum(data);
0047 if nargin == 1, return; end
0048 
0049 % Use stops to restart cumulative sum (tricky vector computation)
0050 stops(1) = 0;
0051 i = find(stops);
0052 k = s(i-1);
0053 dk = diff([0;k]);
0054 z = zeros(size(data));
0055 z(i) = dk;
0056 s = s-cumsum(z);
0057

Generated on Fri 16-Mar-2018 13:00:20 by m2html © 2005