3
$\begingroup$

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

$\endgroup$
7
  • $\begingroup$ 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. $\endgroup$ – MikeLimaOscar Oct 6 '17 at 12:21
  • 1
    $\begingroup$ @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. $\endgroup$ – MikeLimaOscar Oct 6 '17 at 12:35
  • $\begingroup$ @MikeLimaOscar You are right. My mistake, missed that part. $\endgroup$ – ercegovac Oct 6 '17 at 12:41
  • 1
    $\begingroup$ Yes, that makes it a less strange request. You are most of the way there: Count[#, Except[0]] & /@ Transpose[mat] gives {2, 2, 2}. If you might have inexact zeroes use Except[0 | 0.]. $\endgroup$ – MikeLimaOscar Oct 6 '17 at 13:27
  • 1
    $\begingroup$ Is this really a duplicate of the mathematica.stackexchange.com/questions/38624 ? I believe that asks for a total count, not a column count. $\endgroup$ – Alan Oct 6 '17 at 17:52
10
$\begingroup$

I think the simplest version is:

Total @ Unitize @ mat

{2, 2, 2}

$\endgroup$
2
  • $\begingroup$ Nice. I forgot about Unitize. $\endgroup$ – Alan Oct 6 '17 at 16:16
  • $\begingroup$ Thanks. Very simple and elegant answer. It helps a lot. $\endgroup$ – Ni.Kos. Oct 6 '17 at 17:39
3
$\begingroup$
Total@Boole[Thread[# != 0] & /@ mat]
$\endgroup$
0
2
$\begingroup$
 Total@Abs@Sign[mat[[All, 1 ;; Dimensions[mat][[2]]]]]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.