function retval = cfdurm(cf,r)
% usage:  durations = cfdurm(cf,r)
% description: Returns vector of (modified) durations
% of a single cash flow stream vector cf at periodic
% discount rates (in decimal format) specified by the
% vector r. It is assumed that the first entry of cf
% is paid at the end of the first period and subsequent
% entries are paid at the end of successive periods.

% Contact: Tom Shores, tshores@math.unl.edu

% local variables:
% ii: index variable

% a little bit of bulletproofing
if (nargin ~= 2)
  error('pvvar: need two arguments: cf,r');
end
if (sum(r <=-1))
  error('pvvar: discount rate entries of r have to be scalar > -1');
end
if (length(cf) ~= size(cf,1)*size(cf,2))
  error('pvvar: cash flow cf has to be a vector');
end
% make sure cf is row vector
cf = cf(:)';
% the actual calculation
retval = zeros(size(r));
for ii = (1:length(retval))
  retval(ii) = sum((1:length(cf)) .* cf .* (1/(1+r(ii))).^(1:length(cf))) ...
               ./ sum(cf .* (1/(1+r(ii))).^(1:length(cf)));
end
retval = retval ./ (1+r);

