Search code examples
matlabcallbackvariadic-functionscell-arraymatlab-gui

How to pass varargin through callback functions


I'm writing code for a graphics window with several GUI items which run callback functions. Currently I've got a text box and a slider control, and I set things up so that a change to the text box value not only changes the data displayed but also updates the slider position to match that value. The problem I'm running into is in trying to keep my varargin arguments (as entered to the main function when creating the graphics window) from being enclosed in a parent cell variable. When my top-level varargin contains a Value-Parameter pair, varargin is a cell of dimension 1x2 . That's fine. Normally, one can pass all these arguments to an internal function call like this:

function topfunc(varargin)
%code
do_something(varargin{:})

And the function dosomething sees the correct list of arguments. But when I pass the varargins thru the callback definition, as in

txtui = uicontrol(hf,'Style','edit','string',fristframe,'backgroundcolor','y',...
    'position',[10 100 50 20],'Tag','Scaler','UserData',lsatframe,...
    'Callback',{@doslide,adcname,mode,goodframes,{varargin{:}} } ); 

and then the function doslide calls the plotting update function dordplot

 function doslide(theui,event,fileName,mode, goodframes,varargin)
% code snipped...

dordplot(slidinfo,event,fileName,mode,goodframes,varargin{:});
end

Inside doslide, varargin is a 1x1 cell containing the expected 1x2 cell .

I put in a kludge fix in my final function, where the contents of varargin are actually used, with the line

varargin = varargin{:};

But it seems wrong that varargin ever gets wrapped inside a cell in the first place.
Is there a fix, or did I define my callback function call incorrectly?


Solution

  • Per the documentation for varargin:

    When the function executes, varargin is a 1-by-N cell array, where N is the number of inputs that the function receives after the explicitly declared inputs.

    In your callback declaration you have:

    {@doslide,adcname,mode,goodframes,{varargin{:}}}
    

    Wrapping varargin{:} in braces concatenates it back into a cell array, so you are only ever passing 1 input to doslide after goodframes.

    Remove the braces:

    {@doslide, adcname, mode, goodframes, varargin{:}}