% Use Chebfun to find the best approximation to exp(x) from span{1, x, x^2, ..., x^(d-1)}
% Run for various values of "d" and plot the error

 v = chebfun('exp(x)',[0 1]);      % the function to approximate
% v = chebfun('sin(13*x).*exp(x)',[0 1]);      % the function to approximate


 nmax = 15;
 err = zeros(nmax,1);

 figure(1), clf
 plot(v,'b-','linewidth',2)
 hold on 
 for n=1:nmax

    clear Phi                         % build basis vectors for the subspace
    for k=1:n
       Phi{k} = chebfun(sprintf('x.^%d',k-1),[0 1]);  % Phi{k} = x^{k-1}
    end

    G = zeros(n);                      % build the Gram matrix
    for j=1:n, for k=1:n
       G(j,k) = Phi{j}'*Phi{k};        % (Phi_j, Phi_k)
    end, end

    b = zeros(n,1);                    % build the right-hand side
    for k=1:n
       b(k) = Phi{k}'*v;
    end

    c = G\b;                           % find coefficients of best approximation 
   
    w_hat = chebfun('0',[0 1]);        % construct best approximation
    for k=1:n
      w_hat = w_hat + c(k)*Phi{k};   
    end
    
    err(n) = norm(v-w_hat);

    plot(w_hat','m-','linewidth',2)
    xlabel('$x$','interpreter','latex','fontsize',20)
    leg=legend('$v$','$\hat{w}$','location','northoutside','orientation','horizontal');
    set(leg,'fontsize',20,'interpreter','latex')
    fprintf('found best approximation from subspace of dimension n=%d\n', n)
 end

 figure(2), clf
 semilogy([1:nmax], err,'r.-','linewidth',2,'markersize',20)
 xlabel('subspace dimension, $n$','interpreter','latex','fontsize',18);
 ylabel('$\|v - \hat{w}\|$', 'interpreter','latex','fontsize',18);
