Passing predefined variables into matlab's fit function
16 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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 个评论
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
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!