Constraining parameters in nonlinear fit
8 views (last 30 days)
Show older comments
Hi,
I am trying to constrain the parameters of my fit, but I am unable to do so. I am reading data from an oscilloscope and trying to fit a sine wave to it. I'd like to force the amplitude to be positive and the phase angle to be between 0 and 2*pi. The relevant section of my code is below. The way I'm setting the options must be incorrect. Any advice would be much appreciated. Thank you in advance.
Tim
%%Fitting
freq = 25000000; % temporary. Use user input in reality: 10^6*input(prompt);
x = waveform.XData';
v = waveform.YData;
g = fittype(@(a,b,c,x) a*sin(2*pi*freq*x+b)+c);
options = fitoptions(g);
options.Method = NonlinearLeastSquares;
options.Robust = Off;
options.Algorithm = trust-region-reflective;
options.Unknowns = [a,b,c];
options.Lower = [0,0,-Inf];
options.Upper = [+Inf,2*pi,+Inf];
[f,gof,output] = fit(x,v,g,options)
plot(f,x,v)
0 Comments
Answers (2)
John D'Errico
on 20 Feb 2014
The amplitude as a positive number is a meaningless requirement, since a sine wave is both positive and negative. Shift the phase, and the amplitude (as you seem to want to define it) changes sign. All that matter is the absolute value of that coefficient.
As far as something being incorrect, why not tell us why you think it to be incorrect? Are you getting an error? If so, paste in the text of the error.
Shashank Prasanna
on 20 Feb 2014
Regarding the Error: Provide the method with quotations
options.Method = 'NonlinearLeastSquares';
Here is an example that uses NonlinearLeastSquares:
2 Comments
Shashank Prasanna
on 24 Feb 2014
Hi Tim, The last option you tried with fitoptions to provide the options is the recommended approach. For other recommended approaches to specify fit options see the following link:
I'll try and recommend something that may help. Use the cftool app and choose a predefined library function called sum-of-sines as shown here:
Here you can visually verify if you are able to get a fit. If not enforce constraints using the fit options button. If this leads you to a good fit, use the File menu to automatically generate MATLAB code for you.
See Also
Categories
Find more on Linear and Nonlinear Regression in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!