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

조회 수: 4 (최근 30일)
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)
?

답변 (1개)

Mike Croucher
Mike Croucher 2024년 1월 24일
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.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by