alfavictor
alfavictor

Reputation: 63

How to pass an object as argument to an anonymous function in MATLAB?

I'm working on a MATLAB app that programatically creates anonymous functions to evaluate any native MATLAB function and pass it a list of variables as argument. In the example below, 'formula' contains a string with the function and arguments to be evaluated (e.g., "sum( var1, var2 )" ). The formulas sometimes contain function calls nested within function calls, so the code below would be used recursively until obtaining the final result:

Func2 = str2func( sprintf( '@(%s) %s', strjoin( varNames, ',' ), formula ) );

This evaluates fine for native MATLAB functions. But there's a particular case of a function (named Func1) I made myself that not only needs the list of variables but also an object as argument, like this:

function output = Func1( anObject, varNames )
    % do some stuff with the object and the vars
end

For this particular function, I've tried doing this:

  Func2 = str2func( sprintf( '@(%s,%s) %s',  "objectToPassToFunc1", strjoin( varNames, ',' ), "Func1(objectToPass,""" + strjoin( varNames, '","' ) +""")" ) )

...which doesn't throw an error, but Func1 doesn't receive the objectToPassToFunc1, instead it gets values from one of the variables in varNames. And I don't know why.

So how can I correctly pass the object to Func1????

Upvotes: 0

Views: 218

Answers (1)

CroCo
CroCo

Reputation: 5741

Matlab doesn't care about the type of arguments you pass to a function. As a matter of fact, the input could be scalar, vector, matrix, and even an object of a class. See the following example.

classdef ClassA
    methods
        function print(~)
            disp('method print() is called.');
        end
    end
end

This class has only one method. Now, let us define an anonymous function func which accepts one input.

func = @(arg) arg.print;

Notice that we explicitly assume that the input is an object of ClassA. If you pass another type of data to this function, Matlab will throw an error. To test the code,

obj = ClassA;
func = @(arg) arg.print;
func(obj)

To avoid the error, you may need to check the type of the input before using it. For example,

function [] = func(arg)

% check if arg is an object of ClassA
if isa(arg,'ClassA')
    arg.print;
end

end

Now you can pass different types for the input without getting an error.

Upvotes: 1

Related Questions