Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

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

Search the Archive

Re: Functions of Arrays

  • To: mathgroup at smc.vnet.net
  • Subject: [mg102612] Re: [mg102590] Functions of Arrays
  • From: Bob Hanlon <hanlonr at cox.net>
  • Date: Mon, 17 Aug 2009 04:01:23 -0400 (EDT)
  • Reply-to: hanlonr at cox.net

v = Array[a, 5];

m = Array[a, {2, 3}];

Define a function to handle a vector

f[v_?VectorQ] := Total[v^2];

f[v]

a[1]^2 + a[2]^2 + a[3]^2 + a[4]^2 + a[5]^2

f /@ m

{a[1, 1]^2 + a[1, 2]^2 + a[1, 3]^2, 
   a[2, 1]^2 + a[2, 2]^2 + a[2, 3]^2}

Define a function to handle a sequence

g[x__] := Total[{x}^2]

{g[x1], g[x1, x2], g[x1, x2, x3]}

{x1^2, x1^2 + x2^2, x1^2 + x2^2 + x3^2}

f[v] == g[Sequence @@ v]

True

f[{x1, x2, x3}] == g[x1, x2, x3]

True

(f /@ m) == (g[Sequence @@ #] & /@ m )

True

Define a function to handle either a vector or a sequence

h[v_?VectorQ] := Total[v^2]
h[x__] := Total[{x}^2]

h[x1, x2, x3] == h[{x1, x2, x3}] ==
 f[{x1, x2, x3}] == g[x1, x2, x3]

True

Alternatively,

h2[x__] := Total[Flatten[{x}]^2]

h[x1, x2, x3] == h[{x1, x2, x3}] ==
 h2[x1, x2, x3] == h2[{x1, x2, x3}]

True


Bob Hanlon

---- 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.




  • Prev by Date: Re: Is it possible with Mathematica?big problem.thank you
  • Next by Date: Re: Is it possible with Mathematica?big problem.thank you
  • Previous by thread: Re: Functions of Arrays
  • Next by thread: Generating a list numnber in string format