How to pass functions to a Matlab function in the Python API?
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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?
0 Commenti
Risposte (1)
Sarabjit Kheberi
il 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
Vedere anche
Categorie
Scopri di più su Call Python from MATLAB in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!