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:
function z = leastsq(n)
x = (-1.5:0.001:1.5);
y = exp(x);
- Integral of
matrixf = zeros(n,1);
for (grade = 0:n)
matrixf(grade+1,1) = quad(@(x) exp(x)*exp(grade),-1,1);
- Problem: matrix with coefficients of
The code I used here succesfully calculates the coefficients for . I can't find how to make it work for ...
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);
The next step would be to calculate the coefficients to :
Finally the function should be constructed and plotted.
coef = matrixa\matrixf
Any hints or tips would be greatly appreciated.