% Use Chebfun to find the best approximation to exp(x) from span{1, x, x^2, ..., x^(d-1)}

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

 n = input('approximating subspace dimension? '); % the dimension of the approximating subspace

 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

 figure(1), clf
 plot(v,'b-','linewidth',2)
 hold on 
 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')
