Chapter6_Prob19
Chapter6_Prob19
6.19 Modify the MATLAB user-defined function LinearRegression in Program 6-1. In addition to
determining the constants a 1 and a 0 , the modified function should also calculate the overall error E
according to Eq. (6.6). Name the function [a, Er] = LinReg(x,y). The input arguments x and y are
vectors with the coordinates of the data points. The output argument a is a two-element vector with the val-
ues of the constants a 1 and a 0 . The output argument Er is the value of the overall error.
(a) Use the function to solve Example 6-1.
(b) Use the function to solve Problem 6.2.
Solution
The listing of the user-defined function LinReg is:
nx = length(x);
ny = length(y);
if nx ~= ny
disp('ERROR: The number of elements in x must be the same as in y.')
a = 'Error';
Er = 'Error';
else
Sx = sum(x);
Sy = sum(y);
Sxy = sum(x.*y);
Sxx = sum(x.^2);
a1 = (nx*Sxy - Sx*Sy)/(nx*Sxx - Sx^2);
a0 = (Sxx*Sy - Sxy*Sx)/(nx*Sxx - Sx^2);
a=[a1; a0];
% Eq. (5.6)
Excerpts from this work may be reproduced by instructors for distribution on a not-for-profit basis
for testing or instructional purposes only to students enrolled in courses for which the textbook
has been adopted. Any other reproduction or translation of this work beyond that permitted by
Sections 107 or 108 of the 1976 United States Copyright Act without the permission of the
copyright owner is unlawful.
2
Er=sum((y-(a1.*x+a0)).^2);
end
(a) The user-defined function LinReg is used in the Command Window to solve Problem 6.1.
(b) The user-defined function LinReg is used in the Command Window to solve Problem 6.2.
Excerpts from this work may be reproduced by instructors for distribution on a not-for-profit basis
for testing or instructional purposes only to students enrolled in courses for which the textbook
has been adopted. Any other reproduction or translation of this work beyond that permitted by
Sections 107 or 108 of the 1976 United States Copyright Act without the permission of the
copyright owner is unlawful.