Reputation: 351
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.
Upvotes: 0
Views: 481
Reputation: 30047
You said that passing afunction
"was unsuccessful" but didn't show why... that's exactly how I'd solve this issue
% anonymous function
afunction = @(x) x.^2 + 2.*x - 71;
% 1D minimization call
minx = fminsearchbnd(@(x) MWEtestfuntominimize(x, afunction), xguess, xmin, xmax);
Then inside your minimization function...
function g = MWEtestfuntominimize(x, fcn)
g = abs( fcn(x) );
end
To expand on why this works, fminsearchbnd
expects a function with a single input. This is a function with only one input (x
)
@(x) MWEtestfuntominimize( x, afunction )
The function handle (or other variable) afunction
is stored within the anonymous function, with the same value within the workspace at that point. Note that if afunction
changes afterwards, it will not change within your anonymous function.
A simple example would be
a = 2;
f = @(x) x + a;
f(5); % = 7
a = 4; % change 'a' after the definition of 'f'
f(5); % = 7, does not change as f = @(x) x + 2 still
Upvotes: 2