使用 matlabengine 库时从 Python 调用创建的 MATLAB 对象

问题描述 投票:0回答:1

我正在尝试从Python调用MATLAB的scatterInterpolant对象的实例。例如,可以通过 Python 代码在 MATLAB 中使用给定值对两个点进行插值,如下所示:

import matlab.engine
eng=matlab.engine.start_matlab()
a=matlab.double([[1,2],[4,5]])
b=eng.scatteredInterpolant(a,matlab.double([[1],[2]]),'linear')

但是,当我去打电话

b
时,我遇到了错误:

c=eng.b(matlab.double([1,2]))
Unrecognized function or variable 'b'.

---------------------------------------------------------------------------
MatlabExecutionError                      Traceback (most recent call last)
Cell In[17], line 1
----> 1 c=eng.b(matlab.double([1,2]))

File ~/miniconda3/lib/python3.11/site-packages/matlab/engine/matlabengine.py:71, in MatlabFunc.__call__(self, *args, **kwargs)
     68     return FutureResult(self._engine(), future, nargs, _stdout, _stderr, feval=True)
     69 else:
     70     return FutureResult(self._engine(), future, nargs, _stdout,
---> 71                         _stderr, feval=True).result()

File ~/miniconda3/lib/python3.11/site-packages/matlab/engine/futureresult.py:67, in FutureResult.result(self, timeout)
     64     if timeout < 0:
     65         raise TypeError(pythonengine.getMessage('TimeoutCannotBeNegative'))
---> 67 return self.__future.result(timeout)

File ~/miniconda3/lib/python3.11/site-packages/matlab/engine/fevalfuture.py:82, in FevalFuture.result(self, timeout)
     79 if not result_ready:
     80     raise TimeoutError(pythonengine.getMessage('MatlabFunctionTimeout'))
---> 82 self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err)
     83 self._retrieved = True
     84 return self._result

MatlabExecutionError: Undefined function 'b' for input arguments of type 'double'.

c=b(matlab.double([1,2]))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[18], line 1
----> 1 c=b(matlab.double([1,2]))

TypeError: 'matlab.object' object is not callable

如何解决这个问题?

python function matlab calling-convention
1个回答
0
投票

解决了。

原来用 Python 创建的 MATLAB 对象需要手动发送到 MATLAB 引擎。因此,以下代码片段有效:

import matlab.engine
eng=matlab.engine.start_matlab()
a=matlab.double([[1,2],[4,5]])
b=eng.scatteredInterpolant(a,matlab.double([[1],[2]]),'linear')
new_points = matlab.double([[2, 3], [5, 6]])
eng.workspace['new_points']=new_points
eng.workspace['b'] = b
result=eng.eval('b(new_points)')
© www.soinside.com 2019 - 2024. All rights reserved.