MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Counting nonzeros

  • To: mathgroup at
  • Subject: [mg86885] Re: Counting nonzeros
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at>
  • Date: Tue, 25 Mar 2008 01:16:00 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <fs7iml$gma$>

carlos at wrote:
> 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]

The "easiest way" might be in the eye of the beholder! What about the 

     k = Total@Unitize@Flatten@exp (* Fastest Solution *)

     k = Count[exp, x_Integer /; x != 0, -1] (* Slower Solution *)

The first expression uses Unitize to get a list of 0's and 1's only 
(every non zero entry is set to one).

The second expression uses pattern matching and the third parameter of 
Count (setting level to -1 tells Mathematica to look for numbers, 
symbols and other objects that do not have subparts) to count the non 
zero entries.

Here are the timings for each approach (we create some arbitrary integer 
data in the interval [-1, 1] first)

In[1]:= exp = RandomInteger[{-1, 1}, {10, 10, 10}];

In[2]:= Timing@Total@Unitize@Flatten@exp

Out[2]= {0.000083, 702}

In[3]:= Timing@(Length[Flatten[exp]] - Count[Flatten[exp], 0])

Out[3]= {0.000172, 702}

In[4]:= Timing@Count[exp, x_Integer /; x != 0, -1]

Out[4]= {0.000736, 702}


  • Prev by Date: Color Options for PlanarGraphPlot
  • Next by Date: Re: Rotation of 3D objects
  • Previous by thread: Re: Counting nonzeros
  • Next by thread: Re: Counting nonzeros