1

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.

LBogaardt
  • 1,595
  • 1
  • 11
  • 21

1 Answers1

3

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

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • 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 – LBogaardt Apr 13 '18 at 18:20
  • 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. – LBogaardt Apr 13 '18 at 18:26
  • 1
    @LBogaardt If you define plot = {Plot, Plot3D}[[Length[#3]]][#, Evaluate[Sequence @@ (#2 /@ #3)]] &; then call plot[f, {#, -2, 2} &, Variables[f]] – Coolwater Apr 13 '18 at 18:36