Passing predefined variables into matlab's fit function
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Optical_Stress
le 16 Mar 2018
Commenté : Christopher Saltonstall
le 2 Mar 2020
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 commentaires
Réponse acceptée
John D'Errico
le 16 Mar 2018
Modifié(e) : John D'Errico
le 16 Mar 2018
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 commentaires
Christopher Saltonstall
le 2 Mar 2020
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
Plus de réponses (1)
Adam
le 16 Mar 2018
Modifié(e) : Adam
le 16 Mar 2018
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.
Voir également
Catégories
En savoir plus sur Linear and Nonlinear Regression dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!