How to call a Matlab function in Python from matlab.engine using the user's input (variable of type string) as the name of the function?


I have a Matlab function name as a string (the variable name is ‘function_name’), which is an input from a user, and I need to somehow call that function from Python. Below you can see how I was trying to call this function using the variable name, but it exited with the following error: (<class 'matlab.engine.MatlabExecutionError'>, MatlabExecutionError("Undefined function 'chsn_agthm' for input arguments of type 'uint8'.n"), <traceback object at 0x0000015D14323C00>)

import matlab.engine
eng = matlab.engine.start_matlab()
res = eng.function_name(input1, input2, nargout=2)
Asked By: rarush



The problem is that function_name needs to be a statement in the python code, but is given as string. To resolve this, my suggestion would be not to call function_name directly, but to always call MATLAB’s feval function with function_name as first input argument, i.e.

res = eng.feval( function_name, input1, input2, nargout=2)

feval is then called by the MATLAB engine and invokes the function with the name function_name using the other arguments (apart from nargout=2) as input.

For further information on feval please have a look at

Alternative approach:

It might also be possible to construct a string that contains a valid python expression including function_name and then to call this expression using pythons eval().

Answered By: user16372530
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.