skidjoe
skidjoe

Reputation: 659

Curve fitting using for loop for polynomial up to degree i?

I have this hard coded version which fits data to a curve for linear, quadratic and cubic polynomials:

for some data x and a function y

M=[x.^0 x.^1];
L=[x.^0 x.^1 x.^2];

linear = (M'*M)\(M'*y);
plot(x, linear(1)+linear(2)*x, ';linear;r');

deg2 = (L'*L)\(L'*y);
plot(x, deg2(1)+deg2(2)*x+deg2(3)*(x.*x), ';quadratic plot;b');

I am wondering how can I turn this into a for loop to plot curves for degree n polynomials? The part I'm stuck on is the plotting part, how would I be able to translate the increase in the number of coefficients in to the for loop?

what I have:

for i = 1:5 % say we're trying to plot curves up to degree 5 polynomials...
    curr=x.^(0:i);
    degI = (curr'*curr)\(curr'*y);
    plot(x, ???)  % what goes in here<-
end

Upvotes: 2

Views: 366

Answers (2)

Renato Bichara Vieira
Renato Bichara Vieira

Reputation: 131

I believe this should answer your question exactly. You just have to be careful with the matrix dimensions.

for i = 1:5
    curr=x.^(0:i);
    degI = (curr'*curr)\(curr'*y);
    plot(x, x.^(0:i)*degI)
end

Upvotes: 0

gehbiszumeis
gehbiszumeis

Reputation: 3711

If it is only the plotting, you can use the polyval function to evaluate polynomials of desired grade by supplying a vector of coefficients

% For example, some random coefficients for a 5th order polynomial
% degI = (curr'*curr)\(curr'*y)  % Your case 
degi = [3.2755 0.8131 0.5950 2.4918 4.7987 1.5464]; % for 5th order polynomial

x = linspace(-2, 2, 10000);

hold on
% Using polyval to loop over the grade of the polynomials
for i = 1:length(degI)
    plot(x, polyval(degI(1:i), x))
end

gives the all polynomials in one plot

enter image description here

Upvotes: 1

Related Questions