How do I Regression Fit a SinWave to a dataset?
Show older comments
I have a dataset and I want to best fit a sinewave to the plotted data set. This process I think is called a regression...but all the info I come across is about linear regressions only.
Any help would be most appreciated!
1 Comment
Arjun Jaitli
on 20 Nov 2014
My question is for Wayne King - When you finally plot the fitted curve (yhat) and the actual data (y), is yhat the error or in other words the least square difference between the actual data and the sine fit?
Accepted Answer
More Answers (1)
Richard Willey
on 1 May 2012
Here's some simple code that illustrates how to perform nonlinear regression using the 12a release of Statistics Toolbox.
Note: NonLinearModel.fit requires that you provide starting conditions for the various parameters. (Providing good starting conditions helps to ensure that the optimization solvers converge on a global solution rather than a local solution)
%%Generate some data
X = 2* pi*rand(100,1);
X = sortrows(X);
Y = 9 + 7*sin(2*X + 4*pi) + randn(100,1);
scatter(X,Y)
Generate a fit
% Note that we need to pass three sets of input arguments to NonLinearModel
% # The X and Y data
% # A string describing our model
% # Starting conditions for the optimization solvers
% Generate some good starting conditions for the solvers
scatter(X, Y)
hold on
B0 = mean(Y); % Vertical shift
B1 = (max(Y) - min(Y))/2; % Amplitude
B2 = 2; % Phase (Number of peaks)
B3 = 0; % Phase shift (eyeball the Curve)
myFit = NonLinearModel.fit(X,Y, 'y ~ b0 + b1*sin(b2*x1 + b3)', [B0, B1, B2, B3])
% Note that all the coefficient estimates are very good except for b3 where
% any even integer is equally valid
%%look at the complete set of methods
methods(myFit)
%%Generate a plot
hold on
plot(X, myFit.Fitted)
hold off
%%Generate a fit using an alternative syntax
myFit2 = NonLinearModel.fit(X,Y, @(b,x)(b(1) + b(2)*sin(b(3)*x + b(4))), [B0, B1, B2, B3])
Categories
Find more on Linear and Nonlinear Regression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!