Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that a matrix contains a zero column?

Tags:

python

numpy

I have a large matrix, I'd like to check that it has a column of all zeros somewhere in it. How to do that in numpy?

like image 791
siamii Avatar asked Apr 18 '13 20:04

siamii


People also ask

What is a zero column matrix?

A matrix with all zero elements is sometimes called a zero matrix. The sum of a zero matrix and a matrix a of the same type is just a. In symbols the zero matrix is written as 0 (bold face zero) which is different than 0, the real number zero.

Can you remove a row of zeros in a matrix?

Given the matrix A=[1,2;0,0]; To remove the rows of 0 , you can: sum the absolute value of each rows (to avoid having a zero sum from a mix of negative and positive numbers), which gives you a column vector of the row sums. keep the index of each line where the sum is non-zero.


1 Answers

Here's one way:

In [19]: a
Out[19]: 
array([[9, 4, 0, 0, 7, 2, 0, 4, 0, 1, 2],
       [0, 2, 0, 0, 0, 7, 6, 0, 6, 2, 0],
       [6, 8, 0, 4, 0, 6, 2, 0, 8, 0, 3],
       [5, 4, 0, 0, 0, 0, 0, 0, 0, 3, 8]])

In [20]: (~a.any(axis=0)).any()
Out[20]: True

If you later decide that you need the column index:

In [26]: numpy.where(~a.any(axis=0))[0]
Out[26]: array([2])
like image 144
Warren Weckesser Avatar answered Oct 10 '22 08:10

Warren Weckesser