How to call Matlab transfer function from Python using Matlab engine?

20 ビュー (過去 30 日間)
Xin Qi Liu
Xin Qi Liu 2021 年 12 月 25 日
回答済み: Kojiro Saito 2022 年 1 月 18 日
I am trying to use Matlab in Python and was creating a simple transfer function defined as such using the following code:
% Basic imports
from matlab import engine
import matplotlib.pyplot as plt
import numpy as np
import skfuzzy
% Starting Engine
eng = engine.start_matlab()
% Defining my transfer function
num = [27]
den = [1, 1]
sys1 = eng.tf(num, den)
Running this line on Matlab worked just fine:
num = [27]
den = [1, 1]
sys1 = eng.tf(num, den)
But on Python, I receive this error:
---------------------------------------------------------------------------
MatlabExecutionError Traceback (most recent call last)
<ipython-input-24-6f760c3f7a44> in <module>
1 num = [27]
2 den = [1, 1]
----> 3 sys1 = eng.tf(num, den)
C:\Anaconda\lib\site-packages\matlab\engine\matlabengine.py in __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()
72
C:\Anaconda\lib\site-packages\matlab\engine\futureresult.py in result(self, timeout)
65 raise TypeError(pythonengine.getMessage('TimeoutCannotBeNegative'))
66
---> 67 return self.__future.result(timeout)
68
69 def cancel(self):
C:\Anaconda\lib\site-packages\matlab\engine\fevalfuture.py in result(self, timeout)
80 raise TimeoutError(pythonengine.getMessage('MatlabFunctionTimeout'))
81
---> 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:
File C:\Program Files\MATLAB\R2021b\toolbox\control\ctrlmodels\@tf\tf.m, line 370, in tf.tf
The values of the "Numerator" and "Denominator" properties must be arrays of compatible sizes.
  1 件のコメント
VBBV
VBBV 2021 年 12 月 26 日
May be your problem is similar to This

サインインしてコメントする。

回答 (1 件)

Kojiro Saito
Kojiro Saito 2022 年 1 月 18 日
As this document describes, Python's list will be converted to cell array in MATLAB Engine.
Simple way is to convert the list to matlab.double type.
import matlab.engine
# Starting Engine
eng = engine.start_matlab()
# Defining my transfer function
num = matlab.double([27])
den = matlab.double([1, 1])
sys1 = eng.tf(num, den)

Community Treasure Hunt

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

Start Hunting!

Translated by