1

Based on the example given in the documentation, we can call a MATLAB file triarea.m from a python script as follows:

import matlab.engine
eng = matlab.engine.start_matlab()
eng.triarea(nargout=0)

What if, we had a variable in Python with the MATLAB filename input by the user, file_name = 'triarea' then,

eng.file_name(nargout=0)

returns the error

MatlabExecutionError: Undefined function 'file_name' for input arguments of type 'double'.

How can we run the user input MATLAB function in Python?

In my actual problem, the file_name is input while instantiating an object of a class and is stored as an object attribute. Then one of the methods of the object calls this MATLAB file.

2 Answers 2

2

You can use the builtin function gettatr like here:

import matlab.engine
eng = matlab.engine.start_matlab()

file_name = 'triarea'
dynamic_func = getattr(eng, file_name)
dynamic_func(nargout=0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. This worked like a charm for me. I was unaware of this function.
1

You can combine Python's f strings and eval.

An example which uses the function name, in this case plot directly:

eng.plot(eng.magic(4))

An example which evaluates the variable name as the function name:

file_name = 'plot'
eval(f'eng.{file_name}(eng.magic(4))')

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.