Re: More universal way of writing gradient
- To: mathgroup at smc.vnet.net
- Subject: [mg112933] Re: More universal way of writing gradient
- From: "David Park" <djmpark at comcast.net>
- Date: Wed, 6 Oct 2010 03:16:53 -0400 (EDT)
The Presentations package has a command PushOnto that allows more selective application of arguments to patterns anywhere in an expression. So in answer to your first posting: << Presentations` {{Sin}, {Cos}}[x] // PushOnto[Sin | Cos] {{Sin[x]}, {Cos[x]}} In answer to your present question, first note that since Version 7 Mathematica has a nice input form for Function in terms of a Function arrow, entered as esc fn esc or \[Function]. So we can write: f := {x, y} \[Function] Sin[x] Exp[y] grad := u \[Function] {Derivative[1, 0][u], Derivative[0, 1][u]} Then we can use your grad function as follows, but we could also use Through here as well as PushOnto: grad[f][x, y] // PushOnto[_Function] {E^y Cos[x], E^y Sin[x]} I don't really understand your gradList example, so here I just assumed that you wanted the gradient of four different functions in a matrix. f1 := {x, y} \[Function] Sin[x] Exp[y] f2 := {x, y} \[Function] Cos[x] Exp[y] f3 := {x, y} \[Function] Sin[y] Exp[x] f4 := {x, y} \[Function] Cos[y] Exp[x] Map[grad, {{f1, f2}, {f3, f4}}, {2}][x, y] // PushOnto[_Function] {{{E^y Cos[x], E^y Sin[x]}, {-E^y Sin[x], E^y Cos[x]}}, {{E^x Sin[y], E^x Cos[y]}, {E^x Cos[y], -E^x Sin[y]}}} David Park djmpark at comcast.net http://home.comcast.net/~djmpark/ From: Sam Takoy [mailto:sam.takoy at yahoo.com] Hi, My question is not related to the gradient at all, but rather strictly the grammar of Mathematica. Gradient is just an example. My question is: what's the elegant way to write the following function so that it applies to single functions as well as ("rectangular") lists of functions? grad[u_] := {Derivative[1, 0][u], Derivative[0, 1][u]} gradList[u_] := {Map[Derivative[1, 0], u, {2}], Map[Derivative[0, 1], u, {Length[Dimensions[u]]}]} f[x_, y_] := Sin[x] Exp[y] Through[grad[f][x, y]] // MatrixForm gradList[{{f, f}, {f, f}}] // Map[Apply[#, {x, y}] &, #, {Length[Dimensions[#]]}] & // MatrixForm I'm sure I could wrap grad and gradList into a function with an If, but I'm sure there is a more natural way. Thank you in advance, Sam PS: Using Map[Apply[]] in the second case because Through doesn't seem to work with Lists of Lists. This is the subject of an earlier post...