Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

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

Search the Archive

Re: function to check if array is empty

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

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[1]:= 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[1]= {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}

Out[3]= True

Out[5]= {{0, 1, -1}, {0, 0, 0}, {0, 0, 0}}

Out[6]= False

Out[8]= {0.015834, True}

In[9]:= Total[X, -1] == 0

Out[9]= True

In[10]:= 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[10]= {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}

Out[12]= True

Out[14]= {{0, 1, -1}, {0, 0, 0}, {0, 0, 0}}

Out[15]= False

Out[17]= {0.714124, True}

Regards,
-- Jean-Marc


  • Prev by Date: Re: Re: function to check if array is empty
  • Next by Date: Re: Wolfram Workbench user experiences
  • Previous by thread: Re: function to check if array is empty
  • Next by thread: Re: function to check if array is empty