Passing a function as the input argument of another function
10 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 3 Apr 2025
[pfinal,fval,exitflag] = fminunc(@(P)myObjective(intensity,data,P),P0,options);
0 Comments
See Also
Categories
Find more on Web Services in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!