Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2007
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2007

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

Search the Archive

Re: Creating a Listable Function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg73596] Re: Creating a Listable Function
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Thu, 22 Feb 2007 04:44:00 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <ergqjm$j0v$1@smc.vnet.net>

Gregory Lypny wrote:
> Hello everyone,
> 
> I've created a function for population variance, which does not make  
> use of Mathematica's built-in Variance function.
> 
> VarPop[x_] := Total[(x - Mean@x)^2]/Length@x
> 
> How do I need to change the definition to have the function operate  
> across lists much like Total, Mean, and Variance do?
> 
> Regards,
> 
> 	Greg
> 
Hi Gregory,

Assuming I have correctly understood what behavior of Total you are 
referring to, the following version of VarPop (see In[4]) should do what 
you are looking for.
In[1]:=
data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Total[data]
Total[data, 2]

Out[2]=
{12, 15, 18}

Out[3]=
45

In[4]:=
Clear[VarPop];
VarPop[x_, n_Integer:1] /; n < Depth[x] :=
   Nest[Total[(#1 - Mean[#1])^2]/Length[#1] & , x, n]

In[6]:=
VarPop[data]

Out[6]=
  11  8  11
{--, -, --}
  3   3  3

In[7]:=
VarPop[data, 2]

Out[7]=
2
-
9

The expression /Depth[data] - 1/ simulates the value Infinity that can 
be given as second argument to Total.

In[8]:=
VarPop[data, ]

Out[8]=
2
-
9

(Note that, though there are some tests on the arguments, the function 
is not bullet proof: you will have to handle cases such as negative n, say).

Regards,
Jean-Marc


  • Prev by Date: NonLinearRegression Weights
  • Next by Date: Re: Limit of Error function Erf
  • Previous by thread: Re: Creating a Listable Function
  • Next by thread: Re: Creating a Listable Function