Passing a function as the input argument of another function

11 ビュー (過去 30 日間)
Mandy
Mandy 2025 年 4 月 3 日
回答済み: Walter Roberson 2025 年 4 月 3 日
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."

回答 (1 件)

Walter Roberson
Walter Roberson 2025 年 4 月 3 日
[pfinal,fval,exitflag] = fminunc(@(P)myObjective(intensity,data,P),P0,options);

カテゴリ

Help Center および File ExchangeWeb Services についてさらに検索

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by