2

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)
2
  • You might try res = eng.feval( function_name, input1, input2, nargout=2), with function_name being a string of an existing MATLAB function. I cannot test myself, so if it is working, feedback would be welcome. Commented Sep 20, 2022 at 19:21
  • If it is working, I would upgrade the comment to an answer. Commented Sep 20, 2022 at 19:40

1 Answer 1

3

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 https://de.mathworks.com/help/matlab/ref/feval.html.

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.