0
$\begingroup$

I need to define a function let's say f[x_, y_] := x^2 + y^2 such that I need to fix one variable (let's take y = a) and to evaluate the expression which would now be in terms of only the other variable and the fixed variable. So, for input like f[x1, y1], the output must be x1^2 + a^2. For input f[x2, y2], the corresponding output must be x2^2 + a^2 .

$\endgroup$
5
  • $\begingroup$ P.S.: I have just started using mathematica. $\endgroup$ Commented Feb 25, 2015 at 13:42
  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$
    – bbgodfrey
    Commented Feb 25, 2015 at 13:56
  • 3
    $\begingroup$ So why do you even need second argument? $\endgroup$
    – Kuba
    Commented Feb 25, 2015 at 13:58
  • 1
    $\begingroup$ How about defining a new function which is "f with y set to a": fya[x_] := f[x, a] $\endgroup$
    – bill s
    Commented Feb 25, 2015 at 15:00
  • 1
    $\begingroup$ @bills I am generally against such constructs, since they add a dependence on a global variable, in a way that is hard to control, and then it leads to all sorts of troubles. I think, in such cases it is better to either use SubValues: fya[a_][x_]:=f[x,a] (so that then one always uses fya[a] as a "function"), or create a closure at run-time: makeFYA[a_]:= Function[x,f[x,a]], and then fya = makeFYA[a]. The advantage here is that we have a better control. $\endgroup$ Commented Feb 25, 2015 at 15:11

1 Answer 1

1
$\begingroup$

You could define y to be an optional argument which will get the default value a when no value for y is supplied.

 f[x_, y_: a] := x^2 + y^2

 {f[u, v], f[u]}
{u^2 + v^2, a^2 + u^2}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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