How to pass functions to a Matlab function in the Python API?

조회 수: 10 (최근 30일)
onodip
onodip 2018년 11월 2일
댓글: onodip 2018년 11월 5일
Some function need other functions as an arguments. In the Python API currently this leads to a TypeError, as the following example demonstrates with fminsearch:
import matlab.engine
from matlab import double
eng = matlab.engine.start_matlab()
x0 = double([0.25, 0.25])
def rosenbrock_fcn(x):
"""The Rosenbrock function"""
x_0 = x[:-1]
x_1 = x[1:]
rosen = sum((1 - x_0) ** 2) + 100 * sum((x_1 - x_0 ** 2) ** 2)
return double(rosen)
result = eng.fminsearch(rosenbrock_fcn, x0)
print(result)
eng.quit()
This raises the following error:
Traceback (most recent call last):
File "E:/.../matlab4py.py", line 16, in <module>
result = eng.fminsearch(rosenbrock_fcn, x0)
File "E:\...\lib\site-packages\matlab\engine\matlabengine.py", line 66, in __call__
out=_stdout, err=_stderr)
TypeError: unsupported Python data type: function
Is there any walkaround to somehow pass function arguments in the Python API?

답변 (1개)

Sarabjit Kheberi
Sarabjit Kheberi 2018년 11월 5일
You cannot pass a function as an argument to another function when using MATLAB engine with Python. One possible reason for that is the fact that when the function is passed to MATLAB(as an argument), it cannot be interpreted since it is defined in an external language.
As a workaround for the above scenario, you can try implementing 'rosenbrock_fcn' in MATLAB and then pass it as an argument to 'fminsearch' method. From Python end, you can directly call rosenbrock_fcn which would then internally make a call to fminseach and return the result.
Please refer to the below link for a list of supported datatypes which can be used as function arguments: https://www.mathworks.com/help/compiler_sdk/python/pass-data-to-matlab-from-python.html
  댓글 수: 1
onodip
onodip 2018년 11월 5일
I already did that, and that indeed works without problems. I chose I slightly different approach, I implemented rosenbrock_fcn in a separate .m file, and called fminsearch with a string argument for the function. If rosenbrock_fcn is on the Matlab path, this approach works.
However the function should be a Python function. Actually in my real example it would be an instance method, which also sets some of the attributes of the Python class. I think this is not possible, if the function is implemented in Matlab.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by