views:

298

answers:

2

I have two functions: one which creates the UI with buttons, and another one from which I'd like to execute the same function as pressing the button does.

When I dig into the figure with get(gcf,'children') I find the buttons, with a Callback property that looks like this:

ans = 
    [function_handle]
    [              1]
    [              1]
    [1x6 double]

Now, as far as I understand, with the first array element I should be able to execute the same function as is executed when the button is pressed from the UI, but how do I do that? I tried everything, but nothing seems to work.

+1  A: 

You can call it with the () operator, or you can pass it to feval. You'll need to extract it from the cell array first.

x; % holds your ans from original question
fcn = x{1}; % Extract from cell array
fcn(); % call with () syntax
feval(fcn); % call with feval() syntax

If that doesn't work, please post exact code and error message so we can see what's going wrong.

Andrew Janke
Thanks! Great answers both.
JussiR
+2  A: 

From the result you got for the button callback, it appears that the callback has been created in the following way (just for example):

hButton = uicontrol(...,'Callback',{@button_callback,1,1,[1:6]});

where the callback function button_callback is defined as follows:

function button_callback(hObject,eventdata,a,b,c)
  ...
end

Notice that there are two extra arguments in the input argument list for the callback function: hObject (the handle of the object invoking the callback) and eventdata (a structure of event data).

If you want to invoke the function handle with the 3 additional arguments that should be passed to it (1, 1, and a 1-by-6 array), you need to also pass arguments for the hObject and eventdata inputs. Here's how calling the function would look (using your variable ans):

ans{1}(hButton,[],ans{2:end});

You first get the function handle from the cell array (ans{1}) then call it using parentheses as you would any other function. For hObject you can pass the handle to the uicontrol object (or an empty value if it isn't needed), and for eventdata you can just pass an empty value. The additional values are then taken from the cell array as a comma-separated list (ans{2:end}) and each is passed to the function as a separate additional argument.

gnovice
Not much left to ask after this answer. :) What got me was the cell arrays.. Never used them before, so didn't realise i should read them differently ({} instead of []) .
JussiR

related questions