Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to delete all zero columns and rows of a matrix in sympy?

Tags:

python

sympy

I have a matrix like this:

enter image description here

And i would like to remove the zero rows and columns, is there a fast way to do it in sympy? Thanks.


1 Answers

The methods row_del and col_del allow one to delete one row or column at a time. It looks like you may have several of those, so doing this one step at a time might be slow.

I would probably use advanced indexing, passing lists of row and column numbers that are to be kept.

A = Matrix([[0, 0, 0, 0], [0, 1, 2, 3], [0, a, b, c], [0, 7, 8, 9]])
m, n = A.shape
rows = [i for i in range(m) if any(A[i, j] != 0 for j in range(n))]
cols = [j for j in range(n) if any(A[i, j] != 0 for i in range(m))]
A = A[rows, cols]

Alternatively, if you don't mind using NumPy, this can be a little shorter.

import numpy as np
A = Matrix([[0, 0, 0, 0], [0, 1, 2, 3], [0, a, b, c], [0, 7, 8, 9]])
B = np.array(A)
A = Matrix(B[np.ix_(np.any(B != 0, axis=0), np.any(B != 0, axis=1))])

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!