MATLAB: Regression Fit a SinWave to a dataset

regressionsine wave

Ok..I'm almost there. Yesterday I received some help but still have questions (I'm an ultra beginner).
I love baseball and have a data set with the amount of runs scored by the Pittsburgh Pirates for their last 501 games. The data set is sampled by 1. I completed a spectral analysis on that data set and a 3.5678 game cycle is identified in the data set. I would like to know exactly how to: 1.) generate the sin/cos wave with a period of 3.5678 games 2.) fit the newly created sin/cos wave to the Score data set.
Any code or other insight will be MOST appreciated.

Best Answer

Something is probably off in your spectral analysis in identifying the frequency. You have 501 points, which means the spacing between frequencies is 1/501. The closest you can actually get to a period of 3.5678 is 0.2794 cycles/game. So let me use that
y = score(:); %make sure score is a column vector
X = ones(501,3);
n = 0:500;
X(:,2) = cos(2*pi*0.2794*n)';
X(:,3) = sin(2*pi*0.2794*n)';
betahat = X\y;
Fit is
yhat = betahat(1)+betahat(2)*cos(2*pi*0.2794*n)+betahat(3)*sin(2*pi*0.2794*n);
If you have the Statistics Toolbox
[b,bint,r,rint,stats] = regress(y,X);
returns useful information in stats for example:
the R-square statistic, the F statistic and p value for the full model, and an estimate of the error variance.
If you have the Statistics Toolbox and R2012a, you can use
mdl = LinearModel.fit(X,y)
which outputs a table. You can get the coefficients with:
mdl.Coefficients.Estimate