0

Mathematica has a bevy of useful functions (Solve, NDSolve, etc.). These functions output in a very strange manner, ie {{v -> 2.05334*10^-7}}. The major issue is that there does not appear to be any way to use the output of these functions in the program; that is to say all of these appear to be terminal functions where the output is for human viewing only.

I have tired multiple methods (Part, /., etc.) to try to get the output of functions into variables so the program can use them for further steps, but nothing works. The documentation says it can be done but nothing they list actually functions. For example, if I try to use /. to move variables, it continues to treat the variable I assigned to as empty and does symbolic math with it instead of seeing the value. If I try to access the variable ie [[1]], it says the variable is not that deep.

The only method I have found is to put the later steps in separate blocks and copy-paste the output to continue evaluation. Is there any way to get the output of these functions into variables programmatically?

Elliot
  • 5,211
  • 10
  • 42
  • 70

1 Answers1

1

Solve etc. produce a list of replacement rules. So you need to apply these rules to the pattern to be replaced. For instance

solutions = x /. Solve[x^2 == 3, x]

gives you all the solutions in a list.

Here is a quick way to get variable names for the solutions:

x1 = solutions[[1]]
x2 = solutions[[2]]
rerx
  • 1,133
  • 8
  • 19
  • Yup that works. The documentation makes is look like you enter that without `solutions =` and use x directly. – Elliot Mar 31 '14 at 22:33
  • I agree that this may appear slightly intransparent in the beginning. But the Mathematica way is actually quite sensible, which you see once you have a case with solutions in multiple variables. In a language like Python you would probably return a "dictionary" mapping type. – rerx Mar 31 '14 at 22:37
  • I primarily use python. List comprehensions ad numpy arrays make this kind of data handling extremely simple in that language. Then again, to the best of my knowledge this type of solving is impossible in python; the best you could do would be to self-program a very complicated looped search to find a solution sufficiently close for a specific problem, and that ignores symbolic solutions completely. – Elliot Mar 31 '14 at 22:45
  • Conventions are different in Mathematica. `solutions = x /. Solve[x^2 == 3, x]` is actually not very different from writing a Python list comprehension if you think about it. If you like Python, have you had a look at Sympy or Sage? See e.g. http://stackoverflow.com/questions/17847902/what-is-the-difference-between-sympy-and-sage – rerx Mar 31 '14 at 22:51