MATLAB: Linear Regression and Curve Fitting

curve fittinglinear regression

I have a model and some data I'd like to fit to it: X_t = B1*cos(2*pi*omega*t) + B2*sin(2*pi*omega*t) + eta_t
What function would I use to conduct linear regression here, to find B1 and B2?

Best Answer

Fs = 1000;
t = 0:1/Fs:1-1/Fs;
y = 1.5*cos(2*pi*100*t)+0.5*sin(2*pi*100*t)+randn(size(t));
y = y(:);
X = ones(length(y),3);
X(:,2) = cos(2*pi*100*t)';
X(:,3) = sin(2*pi*100*t)';
beta = X\y;
beta(1) is the estimate of the constant term, beta(2) the estimate of B1 and beta(3) the estimate of B2.
If you set the random number generator to its default for reproducible results:
rng default
Fs = 1000;
t = 0:1/Fs:1-1/Fs;
y = 1.5*cos(2*pi*100*t)+0.5*sin(2*pi*100*t)+randn(size(t));
y = y(:);
X = ones(length(y),3);
X(:,2) = cos(2*pi*100*t)';
X(:,3) = sin(2*pi*100*t)';
beta = X\y;
The results are:
beta =
-0.0326
1.5284
0.4643
pretty good.