3) User defined functions and modules:

Functions

The following defines a function q. Note the underscore in x_ and the := sign.

In[41]:=

q[x_] := a + b x + c x^2  RowBox[{{, RowBox[{q[2], ,, RowBox[{q, [, 2.2, ]}], ,, q[u + v]}], }}]

Out[42]=

RowBox[{{, RowBox[{a + 2 b + 4 c, ,, RowBox[{a, +, RowBox[{2.2,  , b}], +, RowBox[{4.84,  , c}]}], ,, a + b (u + v) + c (u + v)^2}], }}]


This function can be used like any other function.

In[43]:=

∫_0^2q[x] x

Out[43]=

2 a + 2 b + (8 c)/3

If you use :=, the right-hand side of the definition is evaluated each time the function is called.  This can often be very confusing!

In[44]:=

a = 13 ; b = 17 ; c = 23 ; RowBox[{{, RowBox[{q[2], ,, RowBox[{q, [, 2.2, ]}], ,, q[u + v]}], }}]

Out[45]=

RowBox[{{, RowBox[{139, ,, 161.72, ,, 13 + 17 (u + v) + 23 (u + v)^2}], }}]

Modules

When a procedure is to complicated for a single function, then use a module. Module allows you to set up local variables with names that are local to the module. A module returns the last thing it computes. Modules are analogous to subroutines in FORTRAN.

In[47]:=

RowBox[{RowBox[{sphere[data_], :=, RowBox[{Module, [, RowBox[{{path, cell, max, min, color}, , ...  ]}]}], ]}], ,, Polygon[cell[[n]]]}], }}], ,, {n, Length[data]}}], ]}]}], }}], ]}]}]}], ]}]}], ;}]

In[52]:=

RowBox[{(* set - up some other stuff *), <br />, <br />, RowBox[{xyz[{λ_, φ_}] := {C ... = count + n + 1, ;}], }}]}], ]}], ;}]}], <br />, conlinessphere = Flatten[conlinessphere, 1] ;}]}]

In[56]:=

data = ReadList["/Users/ross/talks/mathematica/sphere/mss_appx_000000h", Number] ; <br /> Show[sphere[data], ViewPoint4 {1/4, -1, 1/4}, AmbientLightGrayLevel[1]]

[Graphics:../HTMLFiles/index_65.gif]

Out[57]=

⁃Graphics3D⁃


Created by Mathematica  (June 17, 2004)