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.
4 Answers
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]]
.
-
1$\begingroup$ Be warned that this method will evaluate symbols
a1
etc., and expressionsa[1]
etc. Consider guarding withBlock
. $\endgroup$ Commented Aug 12, 2014 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] *)
-
$\begingroup$ Well, but what if one wants to calculate
g[1, 2, 3]
? $\endgroup$– xzczd ♦Commented Feb 25, 2017 at 4:09 -
$\begingroup$ @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. $\endgroup$– kglrCommented Feb 25, 2017 at 4:42
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
-
$\begingroup$
a[1]
,a[2]
,... are variables and not functions, I cannot rename them. $\endgroup$– user18822Commented Aug 12, 2014 at 0:04 -
$\begingroup$ @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. $\endgroup$– AndySCommented Aug 12, 2014 at 0:31
-
$\begingroup$ @AndyS The problem is that I have an expression saved in some variable
V
which includes constants and variablesa[1], a[2], ..., a[i]
. I want to define a functionf[a[1]_, a[2]_, ..., a[i]_] = V
. $\endgroup$– user18822Commented Aug 12, 2014 at 0:40
a[i]
andb[i]
in expressions that are generated in loops in my program. $\endgroup$