[Matlab in python] Does matlab engine supports a .m file whose input is a function handle?

3 visualizaciones (últimos 30 días)
Hi all, I want to use matlab.engine to run .m file.
To make an easy explanation, lets assume I have my_fun.m file with
function res = my_fun(f)
res = f(0)
end
Here f is (or could be) a function hadle like
f = @(x) sin(x)
Now to run this file in python, I should run
import matlab.engine
eng = matlab.engine.start_matlab()
eng.my_fun(nargout=1)
Of course, this code returns an 'lack-of-input' error. How do I input a function handle f into the third line of the code?
Moreover, I ultimately want to do the following:
Is there a way to input a 'python function' like
import numpy as np
def f(x):
return np.sin(x)
?

Respuestas (1)

Mike Croucher
Mike Croucher el 24 de En. de 2024
Unfortunately, the MATLAB Engine for python does not support passing Python functions to MATLAB. Running the following in Python:
import matlab.engine
eng = matlab.engine.start_matlab()
import numpy as np
def f(x):
return np.sin(x)
eng.my_fun(f)
gives
---------------------------------------------------------------------------TypeError Traceback (most recent call last) Cell In[11], line 1----> 1 eng.my_fun(f)File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\matlab\engine\matlabengine.py:64, in MatlabFunc.__call__(self, *args, **kwargs) 61 _stderr_info = '{0}.{1}'.format(_stderr.__class__.__module__, _stderr.__class__.__name__); 62 raise TypeError(pythonengine.getMessage('StderrMustBeStringIO', _sIO_info, _stderr_info)) ---> 64 future = pythonengine.evaluateFunction(self._engine()._matlab, 65 self._name, nargs,args, 66 out=_stdout, err=_stderr) 67 if background: 68 return FutureResult(self._engine(), future, nargs, _stdout, _stderr, feval=True)
TypeError: unsupported Python data type: function
So, we are unable to get a Python function from Python into MATLAB. Even if we could, we'd need to do something different in my_fun.m I think.
I'll raise this as a feature request with development. Can I ask why you need to do this please? Having a solid application can help set priorities.

Categorías

Más información sobre Call MATLAB from Python en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by