clear

N = 15;
a = 50;
f = @(x) atan(a*x); %1./(1+a*x.^2); % f(x) evals

% projection using Legendre polynomials: use legendreP in Matlab
b = zeros(N+1,1);
for i = 0:N
    b(i+1) = integral(@(x) legendreP(i,x) .* f(x),-1,1,'AbsTol',1e-7);
    M(i+1,i+1) = integral(@(x) legendreP(i,x).*legendreP(i,x),-1,1,'AbsTol',1e-7);
end

db = 0e-10*randn(size(b));
cm = (b+db)./diag(M);

% plot result
x = linspace(-1,1,500);
uL = 0;
for i = 0:N
    uL = uL + cm(i+1)*legendreP(i,x);
end
plot(x,f(x),'linewidth',2)
hold on
plot(x,uL,'--','linewidth',2)

%plot(x,f(x)-uL)