在Matlab gui

时间:2016-06-20 17:25:01

标签: matlab callback matlab-figure matlab-guide

我需要根据用户使用Matlab Gui点击的位置处理图像。我找到了建议使用ButtonDownFcn这样的例子:

function buttonSelectSuperpixels_Callback(hObject, eventdata, handles)
h = handles.myCanvas;
set(h,'ButtonDownFcn',@position_and_button);

然后像这样处理子功能position_and_button中的点击点:

function position_and_button(hObject,eventdata)
Position = get( ancestor(hObject,'axes'), 'CurrentPoint' );
Button = get( ancestor(hObject,'figure'), 'SelectionType' );

但是我需要在最后一个子功能中处理一些其他变量。是否可以将handles变量传递给position_and_button并更新它?

我试图将handles作为参数传递,但它似乎没有效果。

1 个答案:

答案 0 :(得分:3)

您可以使用匿名函数将handles结构作为输入添加到回调中

set(h, 'ButtonDownFcn', @(src, evnt)position_and_button(src, evnt, handles))

或单元格数组

set(h, 'ButtonDownFcn', {@position_and_button, handles})

问题是,MATLAB通过值而不是通过引用传递变量。因此,当您定义这些回调时,它们会在创建回调时查看handles副本。这个副本将被传递给另一个函数。此外,您在回调中对handles所做的任何更改都会对另一个副本进行更改,而其他任何功能都不会看到这些更改。

要避免此行为,您可以从回调中的handles检索guidata结构(确保您拥有最新版本)。然后,如果您对其进行任何更改,则需要在这些更改之后保存guidata,并且所有其他功能将能够看到这些更改。

function position_and_button(src, evnt)
    % Get the handles struct
    handles = guidata(src);

    % Now use handles struct however you want including changing variables
    handles.variable2 = 2;

    % Now save the changes
    guidata(src, handles)

    % Update the CData of the image rather than creating a new one
    set(src, 'CData', newimage)
end

在这种情况下,您只需要指定回调函数的默认两个输入。