Repository: sympy/sympy

Issue:
Matrix `row_del` and `col_del` should error on out-of-range
Suppose `A` is an `n` by `n` matrix.  The following should raise an error for out-of-range:

````
A.row_del(n+1)
A.row_del(-(n+1))
````

See also discussion in #9459.

Discussion:

Patch:
diff --git a/sympy/matrices/dense.py b/sympy/matrices/dense.py
index 2295100baa..700b96203a 100644
--- a/sympy/matrices/dense.py
+++ b/sympy/matrices/dense.py
@@ -880,7 +880,9 @@ def row_del(self, i):
         row
         col_del
         """
-        self._mat = self._mat[:i*self.cols] + self._mat[(i + 1)*self.cols:]
+        if i < -self.rows or i >= self.rows:
+            raise IndexError("Index out of range: 'i = %s', valid -%s <= i < %s" % (i, self.rows, self.rows))
+        del self._mat[i*self.cols:(i+1)*self.cols]
         self.rows -= 1
 
     def col_del(self, i):
@@ -904,6 +906,8 @@ def col_del(self, i):
         col
         row_del
         """
+        if i < -self.cols or i >= self.cols:
+            raise IndexError("Index out of range: 'i=%s', valid -%s <= i < %s" % (i, self.cols, self.cols))
         for j in range(self.rows - 1, -1, -1):
             del self._mat[i + j*self.cols]
         self.cols -= 1


Test patch:
diff --git a/sympy/matrices/tests/test_matrices.py b/sympy/matrices/tests/test_matrices.py
index f5fe30bbc8..01f1472884 100644
--- a/sympy/matrices/tests/test_matrices.py
+++ b/sympy/matrices/tests/test_matrices.py
@@ -2467,3 +2467,28 @@ def test_doit():
     a = Matrix([[Add(x,x, evaluate=False)]])
     assert a[0] != 2*x
     assert a.doit() == Matrix([[2*x]])
+
+def test_issue_9457_9467():
+    # for row_del(index)
+    M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    M.row_del(1)
+    assert M == Matrix([[1, 2, 3], [3, 4, 5]])
+    N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    N.row_del(-2)
+    assert N == Matrix([[1, 2, 3], [3, 4, 5]])
+    P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    raises(IndexError, lambda: P.row_del(10))
+    Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    raises(IndexError, lambda: Q.row_del(-10))
+
+    # for col_del(index)
+    M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    M.col_del(1)
+    assert M == Matrix([[1, 3], [2, 4], [3, 5]])
+    N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    N.col_del(-2)
+    assert N == Matrix([[1, 3], [2, 4], [3, 5]])
+    P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    raises(IndexError, lambda: P.col_del(10))
+    Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+    raises(IndexError, lambda: Q.col_del(-10))