Search code examples
rowsympy

SymPy: Delete multiple rows of a matrix


Is there a method to delete multiple rows of a matrix in SymPy (without using NumPy)?

I understand that .row_del() can only delete one row at a time.

from sympy import *

a_1_1, a_1_2, a_1_3 = symbols ('a_1_1 a_1_2 a_1_3')
a_2_1, a_2_2, a_2_3 = symbols ('a_2_1 a_2_2 a_2_3')
a_3_1, a_3_2, a_3_3 = symbols ('a_3_1 a_3_2 a_3_3')

A = Matrix ([
    [a_1_1, a_1_2, a_1_3], 
    [a_2_1, a_2_2, a_2_3], 
    [a_3_1, a_3_2, a_3_3]
])

A.row_del (1 : 2)

does not (yet?) work:

    A.row_del (1 : 2)
                 ^
SyntaxError: invalid syntax

Solution

  • You can use slicing or outer indexing to select the rows that you want:

    In [8]: A = MatrixSymbol('A', 3, 3).as_explicit()
    
    In [9]: A
    Out[9]: 
    ⎡A₀₀  A₀₁  A₀₂⎤
    ⎢             ⎥
    ⎢A₁₀  A₁₁  A₁₂⎥
    ⎢             ⎥
    ⎣A₂₀  A₂₁  A₂₂⎦
    
    In [10]: A[:1,:]
    Out[10]: [A₀₀  A₀₁  A₀₂]
    
    In [11]: A[[0,2],:]
    Out[11]: 
    ⎡A₀₀  A₀₁  A₀₂⎤
    ⎢             ⎥
    ⎣A₂₀  A₂₁  A₂₂⎦