3

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

Ni.Kos.
  • 33
  • 6
  • 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 06 '17 at 12:21
  • 1
    @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 06 '17 at 12:35
  • @MikeLimaOscar You are right. My mistake, missed that part. – ercegovac Oct 06 '17 at 12:41
  • @MikeLimaOscar sorry i didn t specify that it was for non-zero elements. My problem lies in cumulative output. For a single column i just use Count[mat[[All,1;;1]],Except [0], {2}]. – Ni.Kos. Oct 06 '17 at 13:17
  • 1
    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.]. – MikeLimaOscar Oct 06 '17 at 13:27
  • @MikeLimaOscar Thank you very much. This is a very useful specification. – Ni.Kos. Oct 06 '17 at 17:38
  • 1
    Is this really a duplicate of the https://mathematica.stackexchange.com/questions/38624 ? I believe that asks for a total count, not a column count. – Alan Oct 06 '17 at 17:52

3 Answers3

10

I think the simplest version is:

Total @ Unitize @ mat

{2, 2, 2}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
3
Total@Boole[Thread[# != 0] & /@ mat]
Alan
  • 13,686
  • 19
  • 38
2
 Total@Abs@Sign[mat[[All, 1 ;; Dimensions[mat][[2]]]]]
Alucard
  • 2,639
  • 13
  • 22