Search code examples
functionmatlabvariadic-functions

How to call a matlab function specifying explicitly every argument


I am wondering if i can create (and call) a function where i can specify the arguments explicitly, like this:

myFun(arg1 = 1, arg3 = "test_string")

where

function = myFun(arg1,arg2,arg3)

            if exist(arg1,'var')
                %do something
            end
            if exist(arg2,'var')
                %do something
            end
            if exist(arg1,'var')
                %do something
            end

%do something
end

I want to create a class constructor that initialized the class attributes if they are provided in the constructor call.


Solution

  • Have a look at the arguments function mathworks doc. Personally I use this for optional arguments, but you could also use it for your use-case.

    function myRectangle(options)
    arguments
       options.Height (1,1) {mustBeNumeric} = 1
       options.Width (1,1) {mustBeNumeric} = 4
    end
    
    % Function code
    width = options.Width;
    height = options.Height;
    
    area = width * height;
    
    display("rectangle " + width + "x" + height + " has an area of: " + area)
    end
    

    Results in

    myRectangle("Width", 3, "Height", 2)
        "rectangle 3x2 has an area of: 6"
    myRectangle("Height", 2, "Width", 3)
        "rectangle 3x2 has an area of: 6"