Try this: sage: M = random_matrix(GF(2),4,5) sage: len([a for a in M.list() if a]) 12
Here M.list() is a list of all the entries, we select the nonzero ones and count. John Cremona On 15 November 2013 08:25, Eileen Ee <eileen...@gmail.com> wrote: > Hi everyone, > > I want to count the number of non-zero entries in a matrix but I can't find > a Sage command to do this. Instead, I found a NumPy command > numpy.count_nonzero to do it. > > I tested it in the online Sage Cell server: https://sagecell.sagemath.org/ > The code goes like this: import numpy as np > mm = matrix(ZZ, 2, 3, > [1,0,2,0,0,0]) > print mm > print np.count_nonzero(mm) > > It worked in the Sage Cell Server. However, when I tried it out in Sage > v5.12 in Linux. There is an error message: " 'module' object has no > attribute 'count_nonzero' ". Also, when I typed numpy.<tab> to see all > possible commands, numpy.count_nonzero does not appear. It seems as though > there is no such command. > > I am willing to use other simple commands as long as I get to count the > nonzero entries of a matrix. Perhaps someone can help me with this... > > Thanks! > > Cheers, > Eileen. > > -- > You received this message because you are subscribed to the Google Groups > "sage-support" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sage-support+unsubscr...@googlegroups.com. > To post to this group, send email to sage-support@googlegroups.com. > Visit this group at http://groups.google.com/group/sage-support. > For more options, visit https://groups.google.com/groups/opt_out. -- You received this message because you are subscribed to the Google Groups "sage-support" group. To unsubscribe from this group and stop receiving emails from it, send an email to sage-support+unsubscr...@googlegroups.com. To post to this group, send email to sage-support@googlegroups.com. Visit this group at http://groups.google.com/group/sage-support. For more options, visit https://groups.google.com/groups/opt_out.