% p5.m - repetition of p4.m via FFT
%        For complex v, delete "real" commands.


% Differentiation of a hat function:
  N = 24; h = 2*pi/N; x = h*(1:N)';
% *** CHANGE to x = h*(1:N)'; to how it still works, and explain

  v = max(0,1-abs(x-pi)/2); 
  v_bar = my_r2hc(v);
  w_bar = [0 -(1:N/2-1) 0 -(-N/2+1:-1)]' .*  ...
          [v_bar(1);     v_bar(N:-1:N/2+2); ...
           v_bar(N/2+1); v_bar(N/2+1-1:-1:2)];
  w = my_hc2r(w_bar)/N;  % r2hc -> hc2r not normalized
  clf
  subplot(3,2,1), plot(x,v,'.-','markersize',13)
  axis([0 2*pi -.5 1.5]), grid on, title('function')
  subplot(3,2,2), plot(x,w,'.-','markersize',13)
  axis([0 2*pi -1 1]), grid on, title('spectral derivative')

% Differentiation of exp(sin(x)):
  v = exp(sin(x)); vprime = cos(x).*v;  % try different multiples
  
  v_bar = my_r2hc(v);
  w_bar = [0 -(1:N/2-1) 0 -(-N/2+1:-1)]' .*  ... % Im(v_k) = -sin 
          [v_bar(1);     v_bar(N:-1:N/2+2); ...
           v_bar(N/2+1); v_bar(N/2+1-1:-1:2)];
  w = my_hc2r(w_bar)/N;  % r2hc -> hc2r not normalized
  
  subplot(3,2,3), plot(x,v,'.-','markersize',13)
  axis([0 2*pi 0 3]), grid on
  subplot(3,2,4), plot(x,w,'.-','markersize',13)
  axis([0 2*pi -4 4]), grid on
  error = norm(w-vprime,inf);
  text(2.2,1.4,['max error = ' num2str(error)])
