Hello,

I'm having some trouble with finding the least squares approximation (with given n) of $\displaystyle f(x) = e^x$ in [−1, 1] using matlab. The approximation should be of form $\displaystyle P_n(x) = a_0 + a_1x + a_2x^2 + · · · + a_nx_n$.

My Matlab code:

Code:

function z = leastsq(n)

**Plot $\displaystyle f(x) = e^x$**

Code:

x = (-1.5:0.001:1.5);
y = exp(x);
plot(x, y);
xlim([-1.5 1.5])

**Integral of $\displaystyle f_j = \int^1_{-1} 2x\,dx$**

Code:

matrixf = zeros(n,1);
for (grade = 0:n)
matrixf(grade+1,1) = quad(@(x) exp(x)*exp(grade),-1,1);
end

__Problem:__ matrix with coefficients of $\displaystyle P_n(x)$

Code:

for (count = 0:n)
if (count == 0 && mod((1+gradex),2) ~= 0)
matrixa(gradex+1, 1) = 2/(count+1+gradex);
elseif (count ~= 0)
matrixa(gradex+1, count+1) = quad(@(x) exp((count)*x)*exp(gradex),-1,1);
end
end

The code I used here succesfully calculates the coefficients for $\displaystyle f(x) = x$. I can't find how to make it work for $\displaystyle f(x) = e^x$...

The next step would be to calculate the coefficients $\displaystyle c_0$ to $\displaystyle c_n$:

Code:

coef = matrixa\matrixf

Finally the function $\displaystyle P_n(x) = a_0 + a_1x + a_2x^2 + · · · + a_nx_n$ should be constructed and plotted.

Any hints or tips would be greatly appreciated.