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

7 views (last 30 days)
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.

Answers (1)

Kojiro Saito
Kojiro Saito on 18 Jan 2022
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)

Categories

Find more on Marine and Underwater Vehicles in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!