MathGroup Archive 2008

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

Search the Archive

Re: Re: function to check if array is empty

  • To: mathgroup at smc.vnet.net
  • Subject: [mg88451] Re: [mg88329] Re: function to check if array is empty
  • From: Joe Bolte <joeb at wolfram.com>
  • Date: Mon, 5 May 2008 06:17:10 -0400 (EDT)
  • References: <fvbr6d$plc$1@smc.vnet.net> <200805020741.DAA05341@smc.vnet.net>

On May 2, 2008, at 3:41 AM, 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

Tally provides a very fast way to test for any non-zero elements. It  
is faster than the solutions above  except in where there are non-zero  
elements very close to the beginning of the array.

Test Data

array1=ConstantArray[0,{1000,1000}];
array2=DiagonalMatrix[Table[1,{1000}]];
array3=ConstantArray[0,{1000,1000}];
array3[[1000,1000]]=1;

Tally-based solution

In[14]:= ZeroMatrixQ:=Tally[Flatten@#]==={0,Length@Flatten@#}&
In[24]:= Timing[ZeroMatrixQ[#]]&/@{array1,array2,array3}
Out[24]= {{0.008125,True},{0.006914,False},{0.008563,True}}

MatrixQ-based solution

Function[array, Timing[MatrixQ[array, ((# == 0) &)]]] /@ {array1,  
array2,
   array3}

In[29]:= Function[array,Timing[MatrixQ[array,((#==0)&)]]]/ 
@{array1,array2,array3}
Out[29]= {{0.857164,True},{0.000012,False},{0.866723,False}}


Cheers,
Joe


  • Prev by Date: Re: Re: Axes at the origin, for 3D plots/graphs
  • Next by Date: Re: function to check if array is empty
  • Previous by thread: Re: function to check if array is empty
  • Next by thread: Re: Re: function to check if array is empty