【发布时间】:2019-12-30 13:39:15
【问题描述】:
我想在自定义 MATLAB 函数中调用匿名函数。从调用自定义函数的脚本中,我想最小化自定义 MATLAB 函数。我遇到了匿名函数未正确传递给函数的问题。
作为 MWE,我有一个脚本,我在其中定义了一个匿名函数 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);
然后我在另一个文件MWEtestfuntominimize 中编写了一个自定义函数,
function g = MWEtestfuntominimize(x)
g = abs(afunction(x));
end
我希望我的主脚本最小化MWEtestfuntominimize,但似乎MWEtestfuntominimize 无法调用afunction。错误信息是
Undefined function or variable 'afunction'
我尝试将afunction 传递到MWEtestfuntominimize 作为参数,但没有成功。这是通过将最小化调用中的minx 修改为
minx = fminsearchbnd(@(afunction,x) MWEtestfuntominimize(afunction,x), xguess, xmin, xmax);
并将自定义函数修改为
function g = MWEtestfuntominimize(afunction,x)
g = abs(afunction(x));
end
产生的错误是
"afunction" was previously used as a variable, conflicting with its use here as the name of a function or command.
我知道一个解决方案是在 MWEtestfuntominimize 本身中定义匿名函数,但是对于我正在编写的特定程序,我不想这样做。
【问题讨论】:
标签: matlab function anonymous-function