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
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI think the simplest version is:
Total @ Unitize @ mat
{2, 2, 2}
Map[Length, Transpose[mat]]
andConstantArray @@ Dimensions[mat]
are two methods that come to mind. $\endgroup$Transpose
, i.e. if the matrix is not square -- without it you are giving the lengths of the rows. $\endgroup$Count[#, Except[0]] & /@ Transpose[mat]
gives{2, 2, 2}
. If you might have inexact zeroes useExcept[0 | 0.]
. $\endgroup$