6

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.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • I use a large number of a[i] and b[i] in expressions that are generated in loops in my program. –  Aug 11 '14 at 23:40

4 Answers4

1
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] *)
kglr
  • 394,356
  • 18
  • 477
  • 896
  • Well, but what if one wants to calculate g[1, 2, 3]? – xzczd Feb 25 '17 at 04:09
  • @xzczd, maybe we can do something like g[arg1 : a_[___] | x_, arg2 : a_[___] | y_, arg3 : b_[___] | z_] := (arg1 + arg2) arg3 but i am not sure this is what what OP asked. – kglr Feb 25 '17 at 04:42
1

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 *)
seismatica
  • 5,101
  • 1
  • 22
  • 33
0

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. –  Aug 12 '14 at 00: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 00: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. –  Aug 12 '14 at 00:40
0

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

AndyS
  • 135
  • 5
  • 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 05:19