Search code examples
matlaboop

How to get argument name in Matlab constructor


I would like to get the input argument name within the constructor of a class much like below:

classdef Task

    properties
        Name string
    end

    methods
        function this = Task(callback)
            arguments
                callback {isFunctionCallSignal}
            end

            this.Name = inputname(1);
        end
    end

end

Which I use like so:

task = Task(@hello_world)

where @hello_world is a function call signal to an existing function.

How can I get the task.Name to be of value "hello_world" upon instantiation? If if isn't possible within a constructor, is there another way I can achieve this?

Thanks in advance!


Solution

  • I think for this case, you don't care about the name of the variable that was used as an input argument (which in this case doesn't exist because your input argument is simply an expression @hello_world rather than a variable).

    I think what you want here is func2str:

    this.Name = ['@', func2str(callback)];
    

    JFTR, inputname is for cases like this:

    myCallback = @hello_world;
    task = Task(myCallback); % here, inputname returns 'myCallback'
    

    In general, inputname is not a terribly useful function outside of cases where you're trying to implement object display. (Although there are better ways these days)