function du = ddfft(a,b,n,f)
%Derivative of a function using truncated fourier series and fft
%Code By: James Hateley
%
%INPUT
%   a = left endpoint
%   b = right endpoint
%   n = number of points for partition must be 2^k
%   f = function wanting to differentiate
%
%OUTPUT
%   dfft = value of derivative at points
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initialize
if isa(f, 'function_handle')
    x = linspace(a,b,n+1);
    c = fft(f(x),n);
else
    c = fft(f,n);
end
if size(c,2) == 1
    c = c';
end
N = n/2;
%% Load weights for coefficients
jVec = 2*pi/(b-a)*[0:N-1, 0, -N+1:-1];

%% Compute derivative
du = ifft(1i*jVec.*c);

if size(du,2) > 1
    du = du';
end
