'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 1:[1]
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???
Solution 2:[2]
The : syntax to select a slice of items is only supported inside of square brackets in Python. That's why the error is SyntaxError. So even if the row_del function did support deleting multiple rows at once, the syntax for it would not look like row_del(1:2), because that's not valid Python.
Solution 3:[3]
Regarding your follow-up question, part of the beauty of working in Python is that you can write your own utility functions to make things work the way you want. So you could make a function to create a matrix that automatically comes back with indices as desired. Note, too, that selecting rows or columns with a list will put them in the requested order:
>>> a1rc = lambda a,r,c: MatrixSymbol(a, r+1, c+1).as_explicit()[1:,1:]
>>> a1rc("A",3,4)
Matrix([
[A[1, 1], A[1, 2], A[1, 3], A[1, 4]],
[A[2, 1], A[2, 2], A[2, 3], A[2, 4]],
[A[3, 1], A[3, 2], A[3, 3], A[3, 4]]])
>>> _[[2,0],:] # row 2 will come first, then row 0
Matrix([
[A[3, 1], A[3, 2], A[3, 3], A[3, 4]],
[A[1, 1], A[1, 2], A[1, 3], A[1, 4]]])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oscar Benjamin |
| Solution 2 | asmeurer |
| Solution 3 | smichr |
