accessing nested functions from GUI

2020-03-30 06:26发布

I'm trying to have almost all-in-one function that creates GUI and necessary variables in main function and nested functions to be used as callback actions.

When I have

function[]=foo()
A=1;

uicontrol('style','pushbutton','callback','A=bar(A);')

function[OUT]=bar(IN)
OUT=IN+1;

I get error:

Undefined function 'bar' for input arguments of type 'double'.

Error while evaluating uicontrol Callback`

if foo is a script and bar is defined in bar.m file it works. It seems to me that callbacks use in default variables in MATLAB workspace and scripts/fuctions in current working directory. How can I access variables defined IN the calling function (here the variable A) and functions nested in the calling function (here the function bar)

1条回答
啃猪蹄的小仙女
2楼-- · 2020-03-30 06:42

For defining callbacks, I have found the most reliable approach to be using anonymous functions. That being said, if bar is a nested function of foo, then it already has access to A and can modify A.

function = foo()
    A = 1;

    uicontrol('style', 'pushbutton', 'callback', @(s,e)bar())

    % This is a nested function that already has access to A
    function bar()
        A = A + 1;
    end

    % Let's call bar here to demonstrate it updates A
    bar();
    disp(A);
end

Also, your callbacks can't actually pass outputs back to the workspace of the control for which they are the callback. If you want to return a result you would either want to 1) store the result in the UserData of the graphics object, 2) use a nested subfunction as we've shown, or 3) pass a handle to a custom handle object to the callback (classdef object < handle)

查看更多
登录 后发表回答