Functions

Using them

A function in Mathematica is a formalized, named transformation rule. A function may return a symbol, a real number, a complex matrix, another function.... Any mathematical object is an acceptable value for a function. We have seen several built-in functions so far: Solve, Expand , and N are a few examples. A function may be written using mathematical notation, it may be created using programming constructs (like for, if/then, etc.), or it could even be written in another language entirely (Fortran, C, etc.).

All built-in Mathematica functions are named with InitialCapitalLetters (FullSimplify ) and some use abbreviations (NDSolve - Numerical Differential Equation Solver).

Creating them

Input Output Comments
f[x_]:=x2 (none) A simple function definition. Note the underscore (_) that follows the dependent variable name.
f[2]
f[y+z]
4
(y+z)2
The function works with numbers
and expressions.
f[f[f[2]]] 16348 You can nest functions.
?f Global 'f
f[x_] := x2
What is f?
g[x_,y_] := x*y (none) You can have as many arguments as you like.
Clear[f] (none) Deletes the definition of f.

Procedural Functions

You may wish to create more complex functions. Suppose that you wanted to count to 100, and print out a list of each number that is divisible by the argument. Here is one way that you could do it:

sillyCount[n_] := ( Do[ If[Mod[i,n]==0, Print[i]] ,{i,100}]; )

For more information on programming in Mathematica, see the online help.


Next:Graphics
Previous:Doing Math