Passing predefined variables into matlab's fit function

조회 수: 12 (최근 30일)
Optical_Stress
Optical_Stress 2018년 3월 16일
댓글: Christopher Saltonstall 2020년 3월 2일
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.

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by