Thanks, John! That worked well! On a note, before I saw your reply, I used list(M) when I tried to convert the matrix into a list but list(M) contains segregationin the list.
Example: sage: m = matrix(ZZ, 2, 3, [1,0,1,0,1,1]) sage: list(m) [(1, 0, 1), (0, 1, 1)] sage: m.list() [1, 0, 1, 0, 1, 1] What I wanted is a list without the segregation, ie. m.list(), not list(m). I wonder why these two commands produce different results... Thanks, John! You have been a great help! Cheers, Eileen On Friday, 15 November 2013 17:12:06 UTC+8, John Cremona wrote: > > 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 <[email protected] <javascript:>> > 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 [email protected] <javascript:>. > > To post to this group, send email to > > [email protected]<javascript:>. > > > 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 [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/sage-support. For more options, visit https://groups.google.com/groups/opt_out.
