# Count Column Elements in a Matrix [duplicate]

Let a square matrix be:

mat={{1,2,3},{4,5,6},{0,0,0}};

Get a total for each column:

In: Total[mat]

Out: {5,7,9}

I would like to obtain the number of non-zero elements of each column (and the result to be in the form {a,b,c}).

Thanks

• Seems like a strange thing to want for a square matrix but Map[Length, Transpose[mat]] and ConstantArray @@ Dimensions[mat] are two methods that come to mind. – MikeLimaOscar Oct 6 '17 at 12:21
• @ercegovac, In general you need to Transpose, i.e. if the matrix is not square -- without it you are giving the lengths of the rows. – MikeLimaOscar Oct 6 '17 at 12:35
• @MikeLimaOscar You are right. My mistake, missed that part. – ercegovac Oct 6 '17 at 12:41
• Yes, that makes it a less strange request. You are most of the way there: Count[#, Except] & /@ Transpose[mat] gives {2, 2, 2}. If you might have inexact zeroes use Except[0 | 0.]. – MikeLimaOscar Oct 6 '17 at 13:27
• Is this really a duplicate of the mathematica.stackexchange.com/questions/38624 ? I believe that asks for a total count, not a column count. – Alan Oct 6 '17 at 17:52

## 3 Answers

I think the simplest version is:

Total @ Unitize @ mat


{2, 2, 2}

• Nice. I forgot about Unitize. – Alan Oct 6 '17 at 16:16
• Thanks. Very simple and elegant answer. It helps a lot. – Ni.Kos. Oct 6 '17 at 17:39
Total@Boole[Thread[# != 0] & /@ mat]

 Total@Abs@Sign[mat[[All, 1 ;; Dimensions[mat][]]]]