Functions as arguments (Operators)

Notice that if you have a function of a single variable, Mathematica knows what you mean by:

h '[t]

{Cos[t], -Sin[t], 1, 2}

Partial derivatives are also pretty straightforward:

∂_x g[x, y]

{0, 2 x}

Sometimes, it is useful to define a function that operates on other functions.  So, for example, I could define a function to find the derivative matrix for functions from ^2^2:

deriv2By2[expression_] := {∂_x expression, ∂_y expression}//Transpose//MatrixForm

deriv2By2[{x Sin[y], x Cos[y]}]

( {{Sin[y], x Cos[y]}, {Cos[y], -x Sin[y]}} )

deriv2By2[g[x, y]]

( {{0, 1}, {2 x, 0}} )

(Notice that I needed to transpose the matrix to get the rows/columns to work out like we want.  I used MatrixForm just because it looks cool.)  However, you have to be really careful with these.  For example, if I just make one minor little change when calling it:

deriv2By2[{u Cos[v], u Sin[v]}]

( {{0, 0}, {0, 0}} )

The problem is that, when we defined our function, we assumed that our variables would be called x and y, so any other choice of variables gets interpreted as a constant.  One way to fix this would be to explicitly specify your independent variables in the definition:

deriv2By2b[expression_, var1_, var2_] := {∂_var1 expression, ∂_var2 expression}//Transpose//MatrixForm

deriv2By2b[g[u, v], u, v]

( {{0, 1}, {2 u, 0}} )

This now works, though at the cost of a bit of redundancy in calling the function.  (There are fancier tricks we could use to generalize this, but this is a good starting point.)

If you need to access one of the components of a vector, you can use the notation:

g[x, y][[1]]

y

g[x, y][[2]]

x^2

Problem

Define your own functions to compute the gradient (call it myGrad) and divergence (call it myDiv) of an arbitrary function of 3 variables.  (You may not use any of the built-in functions that handle these.)  Demonstrate that each of these actually work for a few different functions.


Created by Mathematica  (February 28, 2007) Valid XHTML 1.1!