Question

Writing Matlab code for the Least Squares Apporximation

Can I please get help with writng the matlab code for the least squares approximation and answering any theoretical questions that may come with it

7. [Least Squares Approximation] Approximate using least squares approximation with polynomials of order 5, 10, 20 on [-5,5]. Does the approximation get better higher order polynomials? Does this seem better than the result from Problem 4, 5, and 6?

0 0
Add a comment Improve this question Transcribed image text
Answer #1
function least_squares(x,n)
%least_squares(x,n) fits a least-squares polynomial of order n through
%a set of data where x and n are the coordinates.
%The output to least_squares(x,n) is the set of coefficients c0, c1,...,cm
%for the least-square polynomial Pm(x) = c0 + c1*x + c2*x^2 + ...+ cm*x^m
%Hence, there will be m+1 values in the vector c.
%A graph displays the set of points and the fitted polynomial
n = size(x,1);
if n == 1
   n = size(x,2);
end

b = zeros(m+1,1);
for i = 1:n
   for j = 1:m+1
      %right-hand side column vector consisting of sums of
      %powers of x multiplied by y's
      b(j) = b(j) + y(i)*x(i)^(j-1);
   end
end


p = zeros(2*m+1,1);
for i = 1:n
   for j = 1:2*m+1
      %sums of powers of x
      p(j) = p(j) + x(i)^(j-1);
   end
end


for i = 1:m+1
   for j = 1:m+1
      %distributing the sums of powers of x in a matrix A
      A(i,j) = p(i+j-1);
   end
end

c = A\b

%creating an x-axis and evaluating the least-ssquare polynomial
%this is only needed for data visualization
t = min(x):0.05:max(x);
n = size(t,2);
for i = 1:n
   f(i) = c(m+1);
   for j = m:-1:1
      f(i) = c(j) + f(i)*t(i);
   end
end

%data visualization
figure
plot(t,f)       %the least_squares polynomial
hold on
plot(x, n, 'r*')        %the data points
grid on
Add a comment
Know the answer?
Add Answer to:
Writing Matlab code for the Least Squares Apporximation Can I please get help with writng the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT