function leastsquare(filename,n) %%input the filename 'data.dat', and %%the degree of polynomial n data=load(filename); %data m X 2 size [m,l]=size(data); m %The matrix A is a (n+1)X(n+1) matrix. %b is the right hand side (n+1)X(1) vector A=zeros(n+1); b=zeros(n+1,1); for i=1:n+1 for j=1:n+1 for k=1:m A(i,j)=A(i,j)+data(k,1)^(i+j-2); %(i,j)element of A end end end for i=1:n+1 for k=1:m b(i)=b(i)+(data(k,1)^(i-1))*data(k,2); %ith element of b end end %find the solution y=inv(A)*b; %define the domain to plot the solution a=min(data(:,1)); b=max(data(:,1)); %divide the domain into 100 small subinterval, %so we are going to evaluate the polynomial %at 101 evenly spaced points in the domain. z=zeros(101,1); for i=1:101 for j=1:n+1 z(i)=z(i)+y(j)*(a+(b-a)*(i-1)/100)^(j-1); end end x=a:(b-a)/100:b; plot(x',z,'red'); hold on; plot(data(:,1),data(:,2)); hold off;