Passing a function as the input argument of another function

조회 수: 14 (최근 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 CenterFile Exchange에서 Web Services에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by