I want to call an anonymous function in a custom MATLAB function. From the script that calls the custom function, I want to minimize the custom MATLAB function. I am having a problem with the anonymous function not being passed correctly to the function.
As a MWE, I have a script, in which I define an anonymous function, afunction,
% directory for minimization algorithm
addpath '/somedirectory/FMINSEARCHBND'
% anonymous function
afunction = @(x) x.^2 + 2.*x - 71;
% 1D minimization guesses
xguess = 20;
xmin = -1000;
xmax = 1000;
% 1D minimization call
minx = fminsearchbnd(@(x) MWEtestfuntominimize(x), xguess, xmin, xmax);
I then have a custom function written in another file MWEtestfuntominimize,
function g = MWEtestfuntominimize(x)
g = abs(afunction(x));
end
I expect my main script to minimize MWEtestfuntominimize, but it seems that MWEtestfuntominimize cannot call afunction. The error message is
Undefined function or variable 'afunction'
I have tried passing afunction through MWEtestfuntominimize as an argument, which was unsuccessful. This was through modifying minx in the minimization call as
minx = fminsearchbnd(@(afunction,x) MWEtestfuntominimize(afunction,x), xguess, xmin, xmax);
and modifying the custom function to
function g = MWEtestfuntominimize(afunction,x)
g = abs(afunction(x));
end
The resulting error was
"afunction" was previously used as a variable, conflicting with its use here as the name of a function or command.
I know a solution would be to define the anonymous function in MWEtestfuntominimize itself, but for the specific program I am writing, I don't want to do this.