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

i1icjdpr  于 2023-11-21  发布在  Matlab
关注(0)|答案(1)|浏览(188)

我尝试从Python调用MATLAB的scatteredInterpolant对象的示例。例如,从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


我该如何解决这个问题?

c9qzyr3d

c9qzyr3d1#

解决了
原来在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)')

字符串

相关问题