Re: HELP: How to do count to the SUB-LIST

• To: mathgroup at smc.vnet.net
• Subject: [mg82128] Re: [mg82096] HELP: How to do count to the SUB-LIST
• From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
• Date: Sat, 13 Oct 2007 03:43:09 -0400 (EDT)
• References: <200710120651.CAA04299@smc.vnet.net> <C25D4397-C5F7-426A-850E-B9E6AA98859B@mimuw.edu.pl>

```On 12 Oct 2007, at 22:30, Andrzej Kozlowski wrote:

>
> On 12 Oct 2007, at 15:51, zhen wrote:
>
>> Hallo, everyone
>>
>> I am new to Mathematica, and I get one problem now, hope to get some
>> help here
>>
>> I got a list like this:
>>
>> {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 0, 0, 0, 1, 0, 0, 0},
>> {0, 0, 0, 0, 1, 1, 0, 0, 2, 0}, {1, 0, 1, 0, 0, 1, 0, 1, 0, 0},
>> {1, 3, 3, 4, 2, 2, 5, 3, 2, 1}, {7, 2, 2, 3, 4, 4, 0, 3, 1, 3}}
>>
>> I need to get a list to show the number of non zero number in each
>> sub
>> list, as to say, I need to get a list like this:
>>
>> {0,3,3,4,10,9}
>>
>> Thanks alot!
>>
>>
>
> There are lots of ways, but one that I think should be pretty fast is:
>
> ls = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 0, 0, 0, 1, 0, 0,
> 0}, {0, 0,
>     0, 0, 1, 1, 0, 0, 2, 0}, {1, 0, 1, 0, 0, 1, 0, 1, 0, 0}, {1, 3,
> 3, 4, 2,
>     2, 5, 3, 2, 1}, {7, 2, 2, 3, 4, 4, 0, 3, 1, 3}};
>
> Total[Transpose[UnitStep[ls - 1]]]
>
> {0, 3, 3, 4, 10, 9}
>
> At first I thought that the following (Mathematica 6 only) variant
> would be faster
>
>  Total[UnitStep[ls - 1], {2}]
>  {0, 3, 3, 4, 10, 9}
>
> but tests seem to show that this isn't the case.
>
> Andrzej Kozlowski
>
>
>

I guess I should add that the above code will only work if (as is
not, you might as well use:

Map[Count[#, x_ /; x != 0] &, ls]

which is the most obvious way to do this in general, but in the non-
negative integer case is much slower than the first method.

Andrzej Kozlowski

```

• Prev by Date: Programming Euler's Method into Mathematica
• Next by Date: Re: How to do count for sub list?????
• Previous by thread: Re: HELP: How to do count to the SUB-LIST
• Next by thread: Re: HELP: How to do count to the SUB-LIST