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

6 vues (au cours des 30 derniers jours)
onodip
onodip le 2 Nov 2018
Commenté : onodip le 5 Nov 2018
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?

Réponses (1)

Sarabjit Kheberi
Sarabjit Kheberi le 5 Nov 2018
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 commentaire
onodip
onodip le 5 Nov 2018
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange

Tags

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by