% xopt = chebopt(f)
%
% Find local optima via a Chebyshev interpolant using a simple-minded Newton
% iteration.

function xopt = chebopt(f)

N = length(f)-1;
[D,x] = cheb(N);
df = D*f;
d2f = D*df;

Iopt = find(sign( df(1:end-1) ) ~= sign( df(2:end) ));
xopt = zeros(length(Iopt),1);

for i = 1:length(Iopt)
ii = Iopt(i);
xest = ( x(ii)+x(ii+1) )/2;
for k = 1:10
dfxest = chebeval(df, xest);
d2fxest = chebeval(d2f, xest);
xest = xest-dfxest/d2fxest;
end
xopt(i) = xest;
end