Passing predefined variables into matlab's fit function

8 ビュー (過去 30 日間)
Optical_Stress
Optical_Stress 2018 年 3 月 16 日
I have a fit using a custom equation' I have some coefficients that are predefined and don't need to be fitted against, how can i pass this into the fit function model without having to write them manually?

採用された回答

John D'Errico
John D'Errico 2018 年 3 月 16 日
編集済み: John D'Errico 2018 年 3 月 16 日
Lots of ways I guess. To make it all explicit, here is an example of one way:
% a fixed parameter:
E = 1.25;
% some data
x = rand(50,1);
y = 1 + 2*sin(x - E) + randn(size(x))/1000;
% establish the model:
mdl = fittype(@(a,b,x) a + b*sin(x - E),'independent','x','coefficients', {'a','b'})
mdl =
General model:
mdl(a,b,x) = a+b*sin(x-E)
% Do the fit. Here, only a and b will be estimated.
ab = fit(x,y,mdl)
Warning: Start point not provided, choosing random start point.
> In curvefit.attention.Warning/throw (line 30)
In fit>iFit (line 299)
In fit (line 108)
ab =
General model:
ab(x) = a+b*sin(x-E)
Coefficients (with 95% confidence bounds):
a = 0.9992 (0.9982, 1)
b = 1.999 (1.997, 2)
As you can see, fit can "see" that E is a parameter, held at a fixed value. I could have gotten rid of the warning by providing starting values for a and b.
The general idea is that I encapsulated the parameter E into the function handle. It is now fixed at the value held by E at the time I created the function handle. Be careful though. Even were you to later change the value of E while that function handle still exists, the function handle will still retain the original value of E.
  2 件のコメント
Optical_Stress
Optical_Stress 2018 年 3 月 16 日
Perfect, thank you!
Christopher Saltonstall
Christopher Saltonstall 2020 年 3 月 2 日
What if the function is more complicated than one line? Can you do something similar when the function is in the form
function output = func(beta,x)
a = beta(1);
b = beta(2);
output = a+b*sin(x-E)
end

サインインしてコメントする。

その他の回答 (1 件)

Adam
Adam 2018 年 3 月 16 日
編集済み: Adam 2018 年 3 月 16 日
Use anonymous functions, e.g.
f = @(x,y) x + y;
g = @(y) f(4,y);
turns f, a function of 2 variables into g, a function of 1 variable with the other hard-coded. More usefully you can equally do e.g.
a = 4;
g = @(y) a + y;
where a has been defined ahead of the function definition so is fixed when you actually call g and you just pass in y.
If it is being passed to some other function as a function handle that expects one variable argument, to be optimised then you can do this to have a function of as many variables as you want, where n-1 of them are predefined.

カテゴリ

Help Center および File ExchangeLinear and Nonlinear Regression についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by