# Is there a way to specify a constant using the fit() function?

85 views (last 30 days)

Show older comments

##### 1 Comment

Caio Vaz Rimoli
on 28 Nov 2018

Well, one way to go is to set the Upper and the Lower bounds with the same value, the value of your constant ( k ).

For example, gauss2 (which is for 2 gaussian peaks):

% General model Gauss2:

% f(x) = a1*exp(-((x-b1)/c1)^2) + a2*exp(-((x-b2)/c2)^2)

k = 0 %%% k is my constant, let's say it is zero

fOps = fitoptions('gauss2');

fOps.Lower=[a1, b1, c1, k, b2, c2]; %%%% lower bounds

fOps.Upper=[A1, B1, C1, k, B2, C2]; %%%% upper bounds

f = fit(x,y,'gauss2',fOps)

Thus the amplitude of the second gaussian is set zero, and the other parameters are free.

### Accepted Answer

### More Answers (4)

Tom Lane
on 9 Feb 2015

The answer you got is correct, so here's how you might do it:

% Get some data

x = sort(10*rand(100,1));

y = 0 + 1*cos(x/2) + 1*sin(x/2) + 2*cos(x) - 3*sin(x) + randn(100,1);

% Suppose we know the first 0 and 1 coefficients. First fit a fourier model.

f1 = fit(x,y,'fourier2')

% Use the results from that as starting values. In the function below

% we omit the constant term and we subtract the known part

fit(x,y-cos(x/2), 'a*sin(x*w) + b*cos(2*x*w) + c*sin(2*x*w)','start',[f1.b1,f1.a2,f1.b2,f1.w])

However, your problem is easier. If you know the frequency, then you just transform the problem into linear regression.

[cos(.5*x),sin(.5*x),cos(x),sin(x)]\y

You can fit this with backslash as above, or with various methods from the Curve Fitting or Statistics Toolbox if you want more statistical results.

Cody Tishchler
on 19 Jun 2018

In case anyone comes across this I had to devise a work around for my application. Since literals will be accepted as constants simply convert the desired constant into a string with num2str and strcat it into the model. Then pass it all as one string into the fit function. Example:

const = num2str(6.283185307*wave_vector/box);

model = strcat('a*sin(', const,'*x+b)');

f = fit(x_data,y_data,model,'StartPoint',[1,0]);

##### 0 Comments

Julia Gala
on 17 Jul 2018

##### 0 Comments

Steven Lord
on 17 Jul 2018

If you build your own fittype object with a custom equation to be fitted, use the 'problem' parameter to specify that a particular variable in the equation to be fitted should be constant. When you call fit with your fittype you need to specify a value for that 'problem' parameter. Alternately you can specify your equation to be fitted as an anonymous function.

See the last two examples on the fittype documentation page for illustrations of those two techniques.

##### 0 Comments

### See Also

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!