1
$\begingroup$

I want to use the Variables[] function to extract the name of the variable of a function, such that I can use it later, e.g. in a Plot[] function.

The following Mathematica code provides a minimal working example:

f=x+x^2
Variables[f]
Plot[f,{x,-2,2}]
Plot[f,{Variables[f],-2,2}]

Please note that I am aware there are better ways to define functions, such as f[x_]:=x+x^2. I also know I could use a Rule[] applied to f to define a new dummy variable within the Plot[] function. That is not the point.

The example I provided is simply a short piece of code to test the way Variables[] works. My question concerns the function Variables[], what it returns and how it can be used.

$\endgroup$
3
$\begingroup$

Variables returns a list, not a symbol, so you need to extract the symbol. Also, Plot has the attribute HoldAll, so you need to circumvent that:

Plot[f, Evaluate @ {First@Variables[f], -2, 2}]

enter image description here

Or:

With[{v = First @ Variables[f]}, Plot[f, {v, -2, 2}]]

enter image description here

$\endgroup$
  • $\begingroup$ Much appreciated. I had actually already tried First[] and Evaluate[] in the following manner: Plot[f, {Evaluate[First[Variables[f]]], -2, 2}]. That does not work. Your way does. +1 $\endgroup$ – LBogaardt Apr 13 '18 at 18:20
  • $\begingroup$ While we're at it, any suggestion for dealing with the possibility of Variables[] returning a list of 2 elements {x, y}? I could put an If[] around it and use Plot[] in one case and Plot3D[] in the other, but that's not elegant. $\endgroup$ – LBogaardt Apr 13 '18 at 18:26
  • 1
    $\begingroup$ @LBogaardt If you define plot = {Plot, Plot3D}[[Length[#3]]][#, Evaluate[Sequence @@ (#2 /@ #3)]] &; then call plot[f, {#, -2, 2} &, Variables[f]] $\endgroup$ – Coolwater Apr 13 '18 at 18:36

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.