Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(40pts) Write a MATLAB program that will calculate the least squares line fit y-

ID: 3708761 • Letter: #

Question

(40pts) Write a MATLAB program that will calculate the least squares line fit y-a+bx to a given set of data points (x, y). Your program should consist of the following function and script: 3. I. A function lin_lsqfit.m capable of calculating the least square estimates of the regression constants a and b. The function has the form [a,b] -lin_lsqfit(x,y), where x and y are the input vectors with the data points. The output variables a, b. You can use any programming approach you want. However, you cannot use any built-in regression functions in MATLAB, such as polyfit. II. A script run_lin_lsqfit.m which does the following: Loads a file containing the data points. A set of data is provided on the Canvas in the file data.txt, which you should use to test program. Do not use the input function to prompt the user for a file name. Just load the file directly from the script file. a. b. Calls lin_Isqfit.m to calculate a and b. c. Plots the data and the least squares fit line on a graph. In the title, write the values of a and b. Make sure to annotate the axes of the graph and include a legend.

Explanation / Answer

%function file

function [a,b]=lin_lsqfit(x,y)
b=sum((x-mean(x)).*(y-mean(y)))./(sum((x-mean(x)).^2));
a=mean(y)-b*mean(x);

%script file
data=load('data.txt');%you havent provided data.txt,so i am assuming it conains 2 columns, x and y
x=data(:,1);
y=data(:,2);
[a,b]=lin_lsqfit(x,y);
xx=min(x):.1:max(x);
yy=a+b*xx;
plot(x,y,'*',xx,yy)
xlabel('x')
ylabel('y')
legend('data points','least squares fit line')
title(['a= ' num2str(a) ' b= ' num2str(b)])