Re: Counting nonzeros
- To: mathgroup at smc.vnet.net
- Subject: [mg86941] Re: Counting nonzeros
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Thu, 27 Mar 2008 08:15:13 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <fs7iml$gma$1@smc.vnet.net> <fsa5gf$ae8$1@smc.vnet.net> <fsd6ga$9af$1@smc.vnet.net>
rfsdias at hotmail.com wrote:
> On 25 mar, 03:18, Peter Pein <pet... at dordos.net> wrote:
>> car... at colorado.edu schrieb:
>>
>>> I want to count the # of NZ entries in an arbitrary multilevel list,
>>> say exp, that contains only integers. Is this the easiest way:
>>> k = Length[Flatten[exp]]-Count[Flatten[exp],0]
>> Count[Flatten[exp],Except[0]] is a bit shorter
>>
>> Peter
>
> try also: Count[exp,Except[0],-1]
Beware that as written the above example will count not only the
non-zero integer value but also the number of intermediate structures
that holds the values. To avoid that, one must use the second argument
of Except, in this case setting it to the pattern _Integer.
Count[exp, Except[0, _Integer], -1]
The following computations should illustrate -- at least I hope! -- what
is going on:
In[1]:= exp = RandomInteger[{0, 1}, {3, 2, 2}]
Out[1]= {{{1, 1}, {1, 1}}, {{1, 0}, {0, 0}}, {{1, 0}, {0, 0}}}
In[2]:= Count[exp, Except[0], -1]
Out[2]= 15
In[3]:= Count[exp, Except[0, _Integer], -1]
Out[3]= 6
In[4]:= Count[Flatten[exp], Except[0]]
Out[4]= 6
In[5]:= Level[exp, {-1}]
% // Length
Out[5]= {1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0}
Out[6]= 12
In[7]:= LeafCount@exp
Out[7]= 22
In[8]:= Level[exp, {-1}, Heads -> True]
% // Length
Out[8]= {List, List, List, 1, 1, List, 1, 1, List, List, 1, 0, List, \
0, 0, List, List, 1, 0, List, 0, 0}
Out[9]= 22
Best regards,
--
Jean-Marc