# Defining a function with parameters as variables

I have an expression V = (a[1] + a[2])b[1]. How would I define a function of a[1], a[2] and b[1]? I'm looking for something like this f[a[1]_,a[2]_,b[1]_]=(a[1] + a[2])b[1] but Mathematica isn't satisfied with that definition.

-
I use a large number of a[i] and b[i] in expressions that are generated in loops in my program. – Dave Aug 11 '14 at 23:40

One way to do this, most likely not the most elegant, is to rename variables of the form a[n] temporarily.

Suppose v = (a[1] + a[2]) b[1]. Then define

f[a1_, a2_, b1_] := Evaluate[v /. {a_[n_] :> ToExpression[ToString[a] <> ToString[n]]}]


With this definition you get the desired result if you evaluate f[a[1],a[2],b[1]].

-
Be warned that this method will evaluate symbols a1 etc., and expressions a[1] etc. Consider guarding with Block. – Mr.Wizard Aug 12 '14 at 5:19

Another alternative:

Clear[f, V]
V = (a[1] + a[2]) b[1];
f[x_, y_, z_] := V /. Thread[Variables[V] :> {x, y, z}];
f[1, 2, 3]
(* 9 *)

-
ClearAll[f,g];
f[a_[1], a_[2], b_[1]] := (a[1] + a[2]) b[1]

f[a[1], a[2], b[1]]
(* (a[1] + a[2]) b[1] *)

f[z[1], z[2], w[1]]
(* w[1] (z[1] + z[2]) *)

f[z[1], z[2], w[2]]
(* f[z[1], z[2], w[2]] --- f undefined for this input pattern *)


Or, more generally,

g[a_[x___], a_[y___], b_[z___]] := (a[x] + a[y]) b[z]

g[a[1], a[3], b[5]]
(* (a[1] + a[3]) b[5] *)
g[a[1], a[3, 2], b[1, 2, 3]]
(* (a[1] + a[3, 2]) b[1, 2, 3] *)
g[w[1], w[3], z[5]]
(* (w[1] + w[3]) z[5] *)
g[w[1], w[], z[1, 2, 3]]
(* (w[] + w[1]) z[1, 2, 3] *)
g[w[1], w[3], z]
(* g[w[1], w[3], z] *)

-

Are you trying to nest functions? i.e. are 'a' and 'b' two functions that you apply the parameter values of '1' or '2' to them and then apply the results to f?

Or in the case that a[1] is simply a name for a variable (something like 'x') Then maybe you're simply looking for f[x_,y_,z_]:=(x+y)z

-
a[1], a[2],... are variables and not functions, I cannot rename them. – Dave Aug 12 '14 at 0:04
@Dave84 As this answer suggests, just define f[x_,y_,z_]:=(x+y)z. Then, f[a[1],a[2],b[1]] gives what you want. – AndyS Aug 12 '14 at 0:31
@AndyS The problem is that I have an expression saved in some variable V which includes constants and variables a[1], a[2], ..., a[i]. I want to define a function f[a[1]_, a[2]_, ..., a[i]_] = V. – Dave Aug 12 '14 at 0:40