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
)
For defining callbacks, I have found the most reliable approach to be using anonymous functions. That being said, if
bar
is a nested function offoo
, then it already has access toA
and can modifyA
.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
)