Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
curve_fitting/least_squares.m
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
15 lines (15 sloc)
516 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function [a,fx,r2] = least_squares(Z,y) | |
%This function accepts a Z-matrix and dependent variable y | |
%as an input. This function returns the vector of best-fit | |
%constants, a, the best-fit function evaluated at each | |
%point, fx, and the coefficient of determination, r2. | |
n=length(Z); | |
Z=Z(:); | |
y=y(:); %convert to column vectors | |
sZ=sum(Z); sy=sum(y); | |
sZ2=sum(Z.*Z); sZy=sum(Z.*y); sy2=sum(y.*y); | |
a(1)=(n*sZy-sZ*sy)/(n*sZ2-sZ^2); | |
a(2)=sy/n-a(1)*sZ/n; | |
r2=((n*sZy-sZ*sy)/sqrt(n*sZ2-sZ^2)/sqrt(n*sy2-sy^2))^2; | |
fx=Z*a; | |
end |