Mathematica Mathematica: Variables and Functions

AI Thread Summary
To evaluate the potential of a physical system at different values of the variable z in Mathematica, users can define the potential as a function, such as potential[z_] := 1/(constant + z). This allows for easy evaluation by calling potential with specific values, like potential[1] or potential[2]. Users have encountered challenges when trying to incorporate outputs from external procedures, but solutions involve using replacement rules, such as func[x_] := potential /. z -> x. The discussion highlights the importance of understanding function definitions and variable substitutions in Mathematica for efficient calculations. Overall, the thread emphasizes sharing knowledge to overcome common programming hurdles in Mathematica.
Niles
Messages
1,834
Reaction score
0
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.


Niles.
 
Physics news on Phys.org
potential[z_]:=1/(constant + z);
 
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]".
 
Thanks for this, I will also check out the reference.Niles.
 
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.Niles.
 
You can use:

potential = 1 + z;
func[x_] := potential /. z -> x
 
USE:
potential = 1 + z
func[z_] = potential​

and it should work.
 
Thanks for the help, it is kind of both of you.Niles.
 
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.
 

Similar threads

Replies
4
Views
2K
Replies
1
Views
2K
Replies
2
Views
2K
Replies
5
Views
2K
Back
Top