What algorithm are you trying to implement here?
CB
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
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
The code I used here succesfully calculates the coefficients for . I can't find how to make it work for ...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 next step would be to calculate the coefficients to :
Finally the function should be constructed and plotted.Code:coef = matrixa\matrixf
Any hints or tips would be greatly appreciated.
Here is some code which I believe may be for the algorithm (linear regression) you are trying to use:
Code:>> x=linespace(-1,1,10); %sample points for the fit >> n=4; %order of polynomial >> xx=zeros(length(x),n); %coefficient array >> for idx=0:3;xx(:,idx+1)=(x.').^(idx);end; >> a=exp(x.'); %right hand side vector >> coeffs=xx\a; %linear least squares solution for coeffs >> pp=zeros(size(x)); %evaluate the polynomial >> for idx=1:n;pp=pp+coeffs(idx)*x.^(idx-1);end; >> plot(x,pp); >> hold on;plot(x,exp(x));hold off
I'm trying to find the solution for
(So I'm not trying to approximate a vector of data points! For which I would use )
I'm trying to find the miminum solution for
I already wrote the code to take the integrals of the n amount of f_j's.
These are all placed in matrixf.
Next I should calculate the coefficient matrix (matrixa) and solve the system by using
coef will then be a vector of length n+1 containing the coefficients to . These will be used to describe the approximating polynomialCode:coef = matrixa\matrixf
I hope I made it a bit clearer. My apologies, all those lines of code make it hard to express myself properly.