Using Mathematica » Basics
Variables
Set
Variables in Mathematica are simple. Just type a name and give it a value with the equals sign ( =
).
Here we'll set the variable thisIsAVariable
thisIsAVariable=10
10
We can suppress the output by ending the line with a semicolon
thisIsAVariable=10;
(for those interested, the semi colon denotes that this is a CompoundExpression
where the return value is Null
)
SetDelayed
A variable can also have a "delayed" value. That is, its value is calculated when requested. Here we'll set the variable randomValuedVariable
.
Use colon-equals ( :=
) to do this.
randomValuedVariable:=RandomReal[];
When we ask for its value, the return value will change every time.
randomValuedVariable
0.12257688426972924`
randomValuedVariable
0.13807713447085046`
Clear
The value of a variable can be removed via Clear
Clear[randomValuedVariable]
The variable now has no value
randomValuedVariable
randomValuedVariable
Simple expressions
We can use variables in expressions to store values for us.
For example, let's do a simple ideal gas law computation for the volume occupied by 2 mols of ideal gas at one atmosphere of pressure and 273 K.
We'll use Mathematica's built in constant data to get the value R in L atm / mol K.
R$gasConstant=
QuantityMagnitude[
UnitConvert[Quantity["MolarGasConstant"],
"Liters"*"Atmospheres"/("Moles"*"Kelvins")]
]
0.0820573382679496654`5.937562804821409
Then we can set up our constants:
n$quantityOfGas=2 (*mols*);
P$externalPressure=1(*atm*);
T$temperatureOfGas=273 (*K*);
And finally calculate our volume:
V$volumeOccupied=n$quantityOfGas*R$gasConstant*T$temperatureOfGas/P$externalPressure
44.8033066943005173068`5.937562804821409