Kingtwofive

Kingtwofive - xsum(i) = sum(x.^(i)); end xmat(1,1) = nx;...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
%%This function calculates the coefficients a0 - a(m+1) of a polynomial %%equation of order m %%y=a0+a1*x^1 . .. a(m+1)*x^m that best fit n data points % Input variables % x = a vector with the coordinates of the x data points % y = a vector with the coordinates of the y data points % m = order of the trial polynomial solution %Output Variables % a = a vector with the a(m+1) coefficients listed in increasing order % Err = squared error/number of points % Also plots points vs. fit equation function [a, Err] = PolyRegression(x,y,m) nx = length(x); %determines length of x and y vectors ny = length(y); if nx ~= ny %checks that vectors are the same length disp('Error: the number of elements in x must be the same as in y') else for i = 1:2*m %calculate the sums of x
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: xsum(i) = sum(x.^(i)); end xmat(1,1) = nx; %x0 term = num points b(1,1) = sum(y); %create b1 point = sum y for j = 2:m+1 %fill in first row of xmatrix xmat(1,j) = xsum(j-1); b(j,1) = sum(x.^(j-1).*y); %complete [b] vector end for i = 2:m+1 for j = 1:m+1 xmat(i,j) = xsum(i + j - 2); %complete [x] matrix end end end a=xmat\b; %use left divide to solve [x][a]=[b] for [a] for i=1:m+1 a2(i)=a(m+2-i); %reverse order of a values for using polyval end for j= 1:nx ycalc = polyval(a2,x); %create calculated y values based of fit coefficients end Err=sum((y-ycalc).^2)/nx; %calculate least squared error figure plot(x,y,'.',x,ycalc,'r') %plot data vs. fit on same axis axis([min(x) max(x) min(y)-5 max(y)+5])...
View Full Document

Ask a homework question - tutors are online