1
$\begingroup$

How can I automatically define a function inside my Mathematica code using a result (expression) that preceded the point of definition.

For example:

tt = x + y
x + y     

f[x_, y_] := 2*tt     

f[1, 1]
2 (x + y)

doesn't give $f$ as 2($x+y$) with $x$ and $y$ being variables here. So, instead of giving f[1,1]=2(1+1)=4 it gave 2(x+y) not recognizing that $x$ and $y$ are meant to be variables.

How can I define $f$ here so that it picks up its definition from the expression of $tt$ automatically, with $x$ and $y$ as variables?

The reason I need this is that it would save me manually copying and pasting the expression x+y into the function defintion, and would make my code run automatically even when tt gives different expressions.

$\endgroup$
2
$\begingroup$

Another option is to use = instead of :=

tt = x + y
f[x_, y_] = 2*tt
f[1, 1]

Mathematica graphics

f[x, 4]

Mathematica graphics

f[x, y]

Mathematica graphics

$\endgroup$
  • $\begingroup$ Great. Many thanks. $\endgroup$ – user135626 Dec 6 '14 at 20:25
1
$\begingroup$

f[x_, y_] := Evaluate[2*tt] would also work.

$\endgroup$
0
$\begingroup$

Try this:

Clear f;
f[u_, v_] := 2*tt /. {x -> u, y -> v} 

f[1, 1]
(*4*)

f[x,y]
(*2 (x + y)*)
$\endgroup$
  • $\begingroup$ Yes, it works. Many thanks. It is a bit inconvenient that Mathematica doesn't have a simpler way to automatically detect these as variables, don't you think? $\endgroup$ – user135626 Dec 6 '14 at 20:02
  • $\begingroup$ if you look at f[x_, y_] := 2*x tt; f[2, 1] // Trace you will see that tt is not evaluated until the arguments of f is passed to the left hand side. that is the nature of functions in MMA. $\endgroup$ – Algohi Dec 6 '14 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.