Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathematica: Variables and Functions

  1. Mar 15, 2012 #1

    I have a long procedure, which calculates the potential of a physical system. The procedure returns something having the form
    Code (Text):

    potential = 1/(constant + z)
    where z is a variable. Now, I need to evaluate potential at different z. I can of course do something like
    Code (Text):

    z = 1;

    and so on, but is there a better way to do this without having to rewrite the procedure? I'm thinking about having something like potential[z], but that is perhaps too late for me to use this, without having to rewrite the whole thing?

    Thanks for any help.

  2. jcsd
  3. Mar 16, 2012 #2
    potential[z_]:=1/(constant + z);
  4. Mar 17, 2012 #3
    As posted above, putting a bracket after the variable makes it a function and putting an underscore after a variable means that you must supply an argument for that variable when you call the function.

    So, if you wanted the variable "U" to be your z, you would type "potentia" into the function as defined by djelovin above. If you wanted z to be equal to .5, you would type "potential[.5]".
  5. Mar 19, 2012 #4
    Thanks for this, I will also check out the reference.

  6. Mar 28, 2012 #5
    I have tried using
    Code (Text):

    potenial = 1+z;
    func[z_] := potential
    but when I call func[1], then I don't get 2 out. Using
    Code (Text):

    func[z_] := 1+z
    is not an option for me, since 1+z is returned to me by some external procedure which I don't command. I only get the output 1+z in the variable potential.

  7. Mar 28, 2012 #6
    You can use:

  8. Mar 28, 2012 #7
    potential = 1 + z
    func[z_] = potential​

    and it should work.
  9. Mar 29, 2012 #8
    Thanks for the help, it is kind of both of you.

  10. Mar 29, 2012 #9
    I have wasted many an hour trying to figure out how to do certain operations in Mathematica so I might as well share what I have learned. I still have not figured out how to use it to make H-R diagrams without writing scripts.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook