       Re: function to check if array is empty

• To: mathgroup at smc.vnet.net
• Subject: [mg88456] Re: function to check if array is empty
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Mon, 5 May 2008 06:18:04 -0400 (EDT)
• Organization: The Open University, Milton Keynes, UK
• References: <fvbr6d\$plc\$1@smc.vnet.net> <4819F79D.4020907@gmail.com> <481E27AC.10008@gmail.com>

```Jean-Marc Gulliet wrote:
> Jean-Marc Gulliet wrote:
>
>> will parr wrote:
>>
>>> is there a function that will check if an array is empty?
>>> i'm looking for a function to return either True (or 1), or False (or
>>> 0) when it checks an array. eg:
>>> X = Array[0 &, {3, 3}]
>>>
>>> then test with function (called ArrayEmpty, for example)
>>>
>>> In: ArrayEmpty[X]
>>>
>>> Out: True
>>
>> If you deal only with m x n rectangular arrays (matrices) you could use
>>
>>     ArrayEmptyQ[arr_List] := MatrixQ[arr, (# == 0 &)]
>>
>> A more general function would be
>>
>>     ArrayEmptyQ[arr_List] :=
>>      If[Count[arr, x_ /; x != 0, -1] != 0, False, True]
>>
>> For instance,
>>
>> X = Array[0 &, {3, 3}]
>> ArrayEmptyQ[arr_List] := MatrixQ[arr, (# == 0 &)]
>> ArrayEmptyQ[X]
>> X[[1, 2]] = 1;
>> X
>> ArrayEmptyQ[X]
>>
>> {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
>>
>> True
>>
>> {{0, 1, 0}, {0, 0, 0}, {0, 0, 0}}
>>
>> False
>
> If speed is important, using *Total* and *Unitize* (to prevent
> cancellation of terms with same magnitude but opposite signs) will be
> faster than the above solution.
>
> In:= X = Array[0 &, {3, 3}]
> ArrayEmptyQ[arr_List] := Total[Unitize[arr], Infinity] == 0
> ArrayEmptyQ[X]
> X[[1, 2]] = 1; X[[1, 3]] = -1;
> X
> ArrayEmptyQ[X]
> X = Array[0 &, {1000, 1000}];
> Timing@ArrayEmptyQ[X]
>
> Out= {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
>
> Out= True
>
> Out= {{0, 1, -1}, {0, 0, 0}, {0, 0, 0}}
>
> Out= False
>
> Out= {0.015834, True}
>
> In:= Total[X, -1] == 0
>
> Out= True
>
> In:= X = Array[0 &, {3, 3}]
> ArrayEmptyQ[arr_List] := MatrixQ[arr, (# == 0 &)]
> ArrayEmptyQ[X]
> X[[1, 2]] = 1; X[[1, 3]] = -1;
> X
> ArrayEmptyQ[X]
> X = Array[0 &, {1000, 1000}];
> Timing@ArrayEmptyQ[X]
>
> Out= {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
>
> Out= True
>
> Out= {{0, 1, -1}, {0, 0, 0}, {0, 0, 0}}
>
> Out= False
>
> Out= {0.714124, True}

Of course, if we know before hand that the list is made of non-negative
elements only (or non-positive only), we can discard the *Unitize*
function, so the resulting function is faster.

In:= X = Array[0 &, {3, 3}]
ArrayEmptyQ[arr_List] := Total[arr, -1] == 0
ArrayEmptyQ[X]
X[[1, 2]] = 1; X[[1, 3]] = -1;
X
ArrayEmptyQ[X]
X = Array[0 &, {1000, 1000}];
Timing@ArrayEmptyQ[X]

Out= {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}

Out= True

Out= {{0, 1, -1}, {0, 0, 0}, {0, 0, 0}}

Out= True

Out= {0.009338, True}

--
Jean-Marc

```

• Prev by Date: Re: Problem/bug with ends of thick lines in graphics
• Next by Date: Want a general method to extract cases resulting from Reduce
• Previous by thread: Re: function to check if array is empty