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

(*Out:*)

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

(*Out:*)

0.122577

randomValuedVariable

(*Out:*)

0.138077

Clear

The value of a variable can be removed via Clear

Clear[randomValuedVariable]

The variable now has no value

randomValuedVariable

(*Out:*)

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")]
    ]

(*Out:*)

0.0820573

n$quantityOfGas = 2 (*mols*);
P$externalPressure = 1(*atm*);
T$temperatureOfGas = 273 (*K*);

V$volumeOccupied = 
 n$quantityOfGas*R$gasConstant*T$temperatureOfGas/P$externalPressure

(*Out:*)

44.8033

results matching ""

    No results matching ""