Matlab匿名回调函数参数

时间:2017-07-25 09:20:54

标签: matlab callback arguments anonymous-function

在Matlab中的模型视图控制器GUI的this示例之后,我有一个关于匿名函数回调输入参数的问题

这是一个视图函数,它创建gui句柄并将它们作为输入参数传递给onChanged回调函数。

function handles = View_TimeDomain(m)
    %VIEW  a GUI representation of the signal model

    % build the GUI
    handles = initGUI();
    onChangedF(handles, m);    % populate with initial values

    % observe on model changes and update view accordingly
    % (tie listener to model object lifecycle)
    addlistener(m, 'f', 'PostSet', ...
        @(o,e) onChangedF(handles,e.AffectedObject));
end

我不太明白的第一件事是,根据Matlab文档,第一个参数必须是事件的来源,第二个文件必须是事件数据(Matlab doc1,{{3} })但在这种情况下它是handles。触发事件时,将按预期调用以下onChangedF函数。

function onChangedF(handles, model)
    % respond to model changes by updating view
    if ~ishghandle(handles.fig), return, end
    set(handles.line, 'XData',model.t, 'YData',model.data)
    set(handles.slider, 'Value',model.f);
end

但是,在这种情况下,handle是包含使用initGui()定义的句柄的结构,而不是事件源。

我想这源于匿名函数的定义:

@(o,e) onChangedF(handles, e.AffectedObject)

我是否正确,假设oonChangedF函数输入中未使用的源。有人可以解释为什么匿名函数的这种语法有效吗? 我认为o也需要成为这个特定回调函数的参数。像这样:

@(o,e) onChangedF(o, handles, e.AffectedObject)

其中附加参数(在结尾处)。 然后使用〜:

来避免这个未使用的参数
function onChangedF(~, handles, model)
    % respond to model changes by updating view
    if ~ishghandle(handles.fig), return, end
    set(handles.line, 'XData',model.t, 'YData',model.data)
    set(handles.slider, 'Value',model.f);
end

1 个答案:

答案 0 :(得分:1)

Anonymous functionsfunction handles的子集,允许您完全定义内联函数,而不是执行其他地方存在的函数的函数句柄。

匿名函数的语法是af = @(arglist)anonymous_function,其功能与:

相同
function af(arglist)
    anonymous_function
end

这意味着您的PostSet回调在功能上等同于:

function PostSet(o,e) 
    onChangedF(handles, e.AffectedObject)
end

满足MATLAB的callback definition要求。

因为handles在您创建PostSet匿名函数时位于函数范围内,所以它也可以在匿名函数回调的范围内使用。这在匿名函数文档的'Variables in the Expression'部分中进行了解释。这也可以使用functions函数进行可视化,该函数提供有关函数句柄的信息:

z = 50;
fh = @(x, y) thing(y, z);

fhinfo = functions(fh);
fhworkspace = fhinfo.workspace{1}

返回:

fhworkspace = 

  struct with fields:

    z: 50
相关问题