Matlab - Least squares approximation of f(x) = e^x
Hello,
I'm having some trouble with finding the least squares approximation (with given n) of
in [−1, 1] using matlab. The approximation should be of form
.
My Matlab code:
Code:
function z = leastsq(n)
- Plot
 = e^x)
Code:
x = (-1.5:0.001:1.5);
y = exp(x);
plot(x, y);
xlim([-1.5 1.5])
- Integral of

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
)
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
. I can't find how to make it work for
...
The next step would be to calculate the coefficients
to
:
Code:
coef = matrixa\matrixf
Finally the function
should be constructed and plotted.
Any hints or tips would be greatly appreciated.