Mathematica: Variables and Functions

  • Mathematica
  • Thread starter Niles
  • Start date
  • #1
1,868
0

Main Question or Discussion Point

Hi

I have a long procedure, which calculates the potential of a physical system. The procedure returns something having the form
Code:
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:
z = 1;
potential

z=2;
potential
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.

Best,
Niles.
 

Answers and Replies

  • #2
28
0
potential[z_]:=1/(constant + z);
 
  • #3
246
6
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]".
 
  • #4
1,868
0
Thanks for this, I will also check out the reference.

Best,
Niles.
 
  • #5
1,868
0
I have tried using
Code:
potenial = 1+z;
func[z_] := potential
but when I call func[1], then I don't get 2 out. Using
Code:
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.

Best,
Niles.
 
  • #6
28
0
You can use:

potential = 1 + z;
func[x_] := potential /. z -> x
 
  • #7
246
6
USE:
potential = 1 + z
func[z_] = potential​

and it should work.
 
  • #8
1,868
0
Thanks for the help, it is kind of both of you.

Best,
Niles.
 
  • #9
246
6
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.
 

Related Threads for: Mathematica: Variables and Functions

Top