Re: Functions of Arrays
- To: mathgroup at smc.vnet.net
- Subject: [mg102650] Re: [mg102590] Functions of Arrays
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Mon, 17 Aug 2009 04:32:19 -0400 (EDT)
- References: <200908161039.GAA01145@smc.vnet.net>
Hi, you should really define your function on lists, of which arrays are a special case. Lists are the data structure most used in Mathematica, and it has many functions to conveniently work with lists - using them, you can make your programs brief and efficient. If you simply want your function to take a list (array) and return a sum of squares, here are some ways: sumsq1[x_List] := Total[x^2]; sumsq2[x_List] := x.x; With the following test array (list): In[1] = test = Range[10] Out[1] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} You get: In[2] = sumsq1[test] Out[2] = 385 In[3] = sumsq2[test] Out[3] = 385 If you plan to use Mathematica often, it is a good idea to read some simple account on basic Mathematica programming with lists. Mathematica book and online documentation are both pretty good. A very good book is by Paul Wellin et al. Also, I have devoted a chapter to this topic in my book: http://www.mathprogramming-intro.org/ It is free, you may want to check it out. Regards, Leonid On Sun, Aug 16, 2009 at 2:39 PM, zak <u.gotzes at googlemail.com> wrote: > Functions can be defined via > > f[x1_, x2_] := x1^2 + x2^2 > > in Mathematica. > > > But how can I manage it to define a function depending on an array? > I would like to do something like > > Array[x,2] > f[x[1]_,x[2]_]:=x[1]^2+x[2]^2 > > because the length of the array varies in my application. > >
- References:
- Functions of Arrays
- From: zak <u.gotzes@googlemail.com>
- Functions of Arrays