【问题标题】:Call an anonymous function within a custom function MATLAB在自定义函数 MATLAB 中调用匿名函数
【发布时间】: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


    【解决方案1】:

    你说通过afunction“不成功”但没有说明原因......这正是我解决这个问题的方法

    % anonymous function
    afunction = @(x) x.^2 + 2.*x - 71;
    % 1D minimization call
    minx = fminsearchbnd(@(x) MWEtestfuntominimize(x, afunction), xguess, xmin, xmax);
    

    然后在你的最小化函数里面......

    function g = MWEtestfuntominimize(x, fcn)
        g = abs( fcn(x) );
    end
    

    为了详细说明其工作原理,fminsearchbnd 需要一个具有单个输入的函数。这是一个只有一个输入的函数 (x)

    @(x) MWEtestfuntominimize( x, afunction )
    

    函数句柄(或其他变量)afunction 存储在匿名函数中,此时工作区中的值相同。请注意,如果 afunction 之后发生更改,它不会在您的匿名函数中更改。

    一个简单的例子是

    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
    

    【讨论】:

    • 这个可行,但是为什么fminsearchbnd的参数只有@(x),而不是@(afunction,x)
    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2016-05-08
    相关资源
    最近更新 更多