LinearRegression

LinearRegression - %checks that vectors are the same length...

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

View Full Document Right Arrow Icon
%%This function calculates the coefficients a1 and a0 of a linear equation %%y=a1*x+a0 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 %Output Variables % a1 = slope % a0 = y-intercept % Err = squared error/number of points function [a0, a1, Err] = LinearRegression(x,y) nx = length(x); %determines length of x and y vectors ny = length(y); if nx ~= ny
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: %checks that vectors are the same length disp('Error: the number of elements in x must be the same as in y') else Sx = sum(x); %Calculates sums of x, y x*y and x^2 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); end for i = 1:nx %calculates squared error per point E(i)=(y(i)-(a1*x(i)+a0))^2; end Err=sum(E)/nx; %sums squared errors and divides by # points...
View Full Document

Ask a homework question - tutors are online