matlaboopmatlab-figureuicontrolmatlab-class

uicontrol callback function too many input arguments


My goal is to get the user's input from a uicontrol text box, do operations on the input and then display the output to another text box. MATLAB gives me the error:

Error using
UnitConverter/lbs2kg
Too many input arguments.

Error in
UnitConverter>@(varargin)app.lbs2kg(varargin{:})
(line 22)
                'Callback',@app.lbs2kg,'String',app.inputMass); 
Error while evaluating UIControl Callback

Here is my code:

classdef UnitConverter < handle


    properties
        Figure                  % Graphics handles
        DispInputMass
        DispOutputMass

        inputMass               %Variables/Class Properties
        outputMass 
    end


    methods

        function app = UnitConverter
            % This is the "constructor" for the class
            % It runs when an object of this class is created
            app.Figure = figure('Name','Unit Converter') ;

            app.DispInputMass = uicontrol('Style','edit',...
                'Callback',@app.lbs2kg,'String',app.inputMass);

            app.DispOutputMass = uicontrol(app.Figure,'Style','edit','Position'...
                 ,[168 100 47 26],'String','kg');
        end



        function lbs2kg(app,evt)
            app.inputMass = get(app.DispInputMass,'string');
            app.outputMass = app.inputMass*.453;
            set(app.DispOutputMass,'string',app.outputMass);
        end


    end
end

Solution

  • The callback method actually has 3 inputs - MATLAB is throwing this error because it is trying to send three inputs to your callback which is written to only accept 2. The 3 inputs are (in order): the main object (app), the object sending the event (uicontrol) and the event (matlab.ui.eventdata.ActionData).

    You can change the code to the following to get it to work:

    function lbs2kg(app, obj, evt)
        app.inputMass = get(app.DispInputMass,'string');
        app.outputMass = app.inputMass*.453;
        set(app.DispOutputMass,'string',app.outputMass);
    end
    

    Additionally you can change the first line of the function to the following:

    function lbs2kg(varargin)
    

    Breakpoint the code at the first line of the callback and investigate the contents of varargin. For more help about varargin see here (http://www.mathworks.com/help/matlab/ref/varargin.html)