I know that in matlab I can do the following:
s = tf('s')
G11 = (s 1)/(s 2)
G12 = 1/(2*s 1)
G21 = 1/(3*s 1)
G22 = 1/(4*s 1)
A = [G11 G12; G21, G22]
Ai = inv(A)
bode(A)
and it will work just fine. In python, I tried to do something similar:
import control as co
import numpy as np
s = co.tf('s')
G11 = (s 1)/(s 2)
G12 = 1/(2*s 1)
G21 = 1/(3*s 1)
G22 = 1/(4*s 1)
A = np.array([[G11, G12], [G21, G22]])
Ai = np.linalg.inv(A)
co.bode(A)
But this doesnt work - numpy doesnt know how to invert this matrix.
Is there a good way to do this in python? I know that I can use scipy with s being a symbol, but I think that doesnt help me when using the others tools in the control toolbox.
Edit:
numpy returns the following error:
---------------------------------------------------------------------------
UFuncTypeError Traceback (most recent call last)
<ipython-input-1-ec46afd90eb6> in <module>
10
11 A = np.array([[G11, G12], [G21, G22]])
---> 12 Ai = np.linalg.inv(A)
13 co.bode(A)
<__array_function__ internals> in inv(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/numpy/linalg/linalg.py in inv(a)
543 signature = 'D->D' if isComplexType(t) else 'd->d'
544 extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
--> 545 ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
546 return wrap(ainv.astype(result_t, copy=False))
547
UFuncTypeError: Cannot cast ufunc 'inv' input from dtype('O') to dtype('float64') with casting rule 'same_kind'
CodePudding user response:
Numpy (hint: it's right in the name) is a numerics library only; it does not do symbolic math. Sympy (also in the name) does symbolic math, so use it:
import sympy
s = sympy.Symbol('s', imaginary=True)
g11 = (s 1)/(s 2)
g12 = 1/(2*s 1)
g21 = 1/(3*s 1)
g22 = 1/(4*s 1)
A = sympy.Matrix((
(g11, g12),
(g21, g22),
))
sympy.pprint(A.inv())
with output
⎡ 3 2 3 2 ⎤
⎢ 6⋅s 17⋅s 11⋅s 2 - 12⋅s - 31⋅s - 15⋅s - 2 ⎥
⎢ ─────────────────────── ────────────────────────── ⎥
⎢ 3 2 3 2 ⎥
⎢ 6⋅s 7⋅s - 3⋅s - 1 6⋅s 7⋅s - 3⋅s - 1 ⎥
⎢ ⎥
⎢ 3 2 4 3 2 ⎥
⎢- 8⋅s - 22⋅s - 13⋅s - 2 24⋅s 50⋅s 35⋅s 10⋅s 1⎥
⎢───────────────────────── ────────────────────────────────⎥
⎢ 3 2 3 2 ⎥
⎣ 6⋅s 7⋅s - 3⋅s - 1 6⋅s 7⋅s - 3⋅s - 1 ⎦
CodePudding user response:
It looks like control.tf
returns an object of class control.TransferFunction
. This is different from the MATLAB version that returns a symbolic function object.
By looking through the documentation, I don’t see a built-in way to convert a control.TransferFunction
object to a symbolic function object, but I did see there are the num
and den
methods, you could construct a symbolic function using those values. And then you can apply the answer by Reinderien.