function v=ppval1(pp,xx)
%PPVAL  Evaluate first derivative of piecewise polynomial.
%   V = PPVAL1(PP,XX) returns the value of the derivative at the points XX of the piecewise
%   polynomial contained in PP, as constructed by SPLINE or the spline utility
%   MKPP.
%
%   V = PPVAL1(XX,PP) is also acceptable, and of use in conjunction with
%   FMINBND, FZERO, QUAD, and other function functions.
%
%   See also SPLINE, MKPP, UNMKPP.

%   Carl de Boor 7-2-86
%   Copyright 1984-2001 The MathWorks, Inc.
%   $Revision: 5.15 $  $Date: 2001/04/15 11:59:07 $

if isstruct(xx) % we assume that ppval(xx,pp) was used
   temp = xx; xx = pp; pp = temp;
end

[mx,nx] = size(xx); lx = mx*nx; xs = reshape(xx,1,lx);
% if necessary, sort xx 
tosort=0;
if any(diff(xs)<0)
   tosort=1;[xs,ix]=sort(xs);
end

% take apart pp
[x,c,l,k,d]=unmkpp(pp);

% for each data point, compute its breakpoint interval
[ignored,index] = sort([x(1:l) xs]);
index = max([find(index>l)-(1:lx);ones(1,lx)]);

% now go to local coordinates ...
xs = xs-x(index);

if d>1 % ... replicate xs and index in case pp is vector-valued ...
   xs = reshape(xs(ones(d,1),:),1,d*lx);
   index = d*index; temp = [-d:-1].';
   index = reshape(1+index(ones(d,1),:)+temp(:,ones(1,lx)), d*lx, 1 );
end

% ... and apply nested multiplication:

   v = (k-1)*c(index,1).';
   for i=2:k-1
      v = xs.*v + (k-i)*c(index,i).';
   end

v = reshape(v,d,lx);
if tosort>0, v(:,ix) = v; end
v = reshape(v,d*mx,nx);
