Passing a function as the input argument of another function
15 次查看(过去 30 天)
显示 更早的评论
Hi,
I am trying to optimise the parameters of my model to some experimental data. I obviously didnt have the inputs correct...
What shall I include in the input arguments? I want matlab to know I am optimising P.
Huge huge thanks!
mandy
% My parameters that's already in the workspace
l = 180;
v_correct = 37;
data = I;
%freq in work space
P0 = [1e9,1.8,1e-4,0.25,1000,1];
% My 1st function generates my model, I want to then pass my model to a
% second function that finds the chi squares between my model and the data
intensity = @(P) myIntensity(l,v_correct,freq,P);
% My 2nd function finds chi squares and gradient, error
function [chisqr,grad] = myObjective(intensity,data,P)
chisqr = sum((data - intensity(P)).^2);
grad = 2*sum(data - intensity(P));
end
ERROR:
"Not enough input arguments.
Error in untitled>myObjective (line 10)
chisqr = sum((data - intensity(P)).^2);"
% I then pass the 2nd function which is the objective to the fminunc
% function, but this is not correct
options = optimoptions('fminunc','Algorithm','trust-region','SpecifyObjectiveGradient',true);
[pfinal,fval,exitflag] = fminunc(@myObjective,P0,options);
ERROR:
"Invalid use of operator.
Undefined function 'objective' for input arguments of type 'double'.
Error in fminunc (line 242)
[f,GRAD] = feval(funfcn{3},x,varargin{:});
Error in untitled (line 15)
[pfinal,fval,exitflag] = fminunc(@objective,P0,options);
Caused by:
Failure in initial objective function evaluation. FMINUNC cannot continue."
0 个评论
回答(1 个)
Walter Roberson
2025-4-3
[pfinal,fval,exitflag] = fminunc(@(P)myObjective(intensity,data,P),P0,options);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Web Services 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!