Task 5: Write a script for linear least square regression. (10points) Do not use
ID: 3841804 • Letter: T
Question
Task 5: Write a script for linear least square regression. (10points) Do not use any of MATLAB's built in functions or commands. This MUST be implemented using matrix and vector components via FOR loops in your construction. Spring 2017 EEN 357 Engineering Analysis for Mechanical Engineers For a given dataset of independent variable x, and dependent variable y where i 1,2, ....n the linear regression model is where ao and an are regression parameters. The least squares estimation is used to minimize the sum of the n squared errors the parameters can be computed as: Using the algorithm, write the function for linear approximation of y: This function must have the interface DATA, YDATA.) where XDATA and YDATA are the vectors of n data points and it should return the value of at given x. Ifxis a vector, the function should return a vector y wfhere each element of ycorresponds to the element of X.Explanation / Answer
Matlab function linearegress.m
function y = linearegress(XDATA,YDATA,x)
n = length(XDATA); % Number of data points
sumX = 0;sumY = 0;sumXY = 0;sumXsq = 0; % initilization of variables
for i = 1:n % sum of all x
sumX = sumX + XDATA(i); % computing summation of x
end
for i = 1:n % // sum of all y
sumY = sumY +YDATA(i); % computing summation of y
end
for i = 1:n % sum of all (xy)
sumXY = sumXY + XDATA(i)*YDATA(i); % computing summation of x*y
end
for i = 1:n % sum of all x^2
sumXsq = sumXsq +XDATA(i)*XDATA(i); % computing summation of x^2
end
m = ((n*sumXY) - (sumX*sumY)) / ((n*sumXsq) - (sumX*sumX));
b = ((sumY - (m*sumX)) / n);
y = m*x+b; % Computing the value of y corresponding to x
end
Testing the code
>> XDATA = 0:100;
>> YDATA = 2*X+1;
>> x = [1.5 2.5 50.5 4];
>> y = linearegress(XDATA,YDATA,x)
y =
4 6 102 9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.