I apologize in advance if this is a duplicate. Variables has a strange behavior when it encounters powers:

  w = s1^(n + 2) s2;
  (*{s1, s1^n, s2}*)

I'd have expected {s1, s2, n},

On the other hand

 w = s1^2 s2;
 (*{s1, s2}*) 

yields what one expects. I wonder if there is a way to get the expected result in the first example.


marked as duplicate by Bob Hanlon, m_goldberg, J. M. will be back soon Apr 19 '17 at 0:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ Perhaps this is the issue: Under the Possible Issues section of the documentation for Variables, it says: "Variables looks for variables only inside sums, products, and rational powers". That indicates to me that since it can't assume that n+2 is rational, it fails. $\endgroup$ – march Apr 18 '17 at 22:04
  • $\begingroup$ Block[{n = 2}, Variables[w]] gives the answer you are looking for (the 2 can be replaced with an arbitrary integer). Does this suit your needs? $\endgroup$ – mikado Apr 18 '17 at 22:13
  • $\begingroup$ @march yes, thanks, that's the issue. I'm wondering if there is a way to fix this, i.e. to get the expected result. $\endgroup$ – user46676 Apr 18 '17 at 22:13
  • $\begingroup$ @mikado well, this does not list n. Of course I can find out by hand what the variables are, but I'm wondering if Mathematica can do it for me. $\endgroup$ – user46676 Apr 18 '17 at 22:15
  • $\begingroup$ The question is what is a variable. You could do Union@Cases[w, _Symbol,Infinity], but if you also want to get an f from, say f[n], then you might want to use Union@Select[Cases[w, _Symbol, Infinity, Heads -> True], Context[#] =!= "System" &]' $\endgroup$ – Rolf Mertig Apr 18 '17 at 22:27

That's because Variables[w] only show the independent variables inside sums, products, and rational powers, according to the documentation:


So, even if you put Variables[E^x] the result will show {}. In you example, s1^(n + 2) s2 is the same as s1^n s1^2 s2 and the independet variables for that expression are s1, s1^n and s2.