MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: More universal way of writing gradient

  • To: mathgroup at smc.vnet.net
  • Subject: [mg112919] Re: More universal way of writing gradient
  • From: Bob Hanlon <hanlonr at cox.net>
  • Date: Wed, 6 Oct 2010 03:14:12 -0400 (EDT)

Perhaps a different approach would work easier

Clear[grad]

grad[f_][arg__] := Module[{v, vars},
  vars = Table[v[i], {i, Length[{arg}]}];
  (D[f @@ vars, #] & /@ vars) /.
   Thread[vars -> {arg}]]

grad[f_List][arg__] := grad[#][arg] & /@ f

grad[f][x, y]

{Derivative[1, 0][f][x, y], Derivative[0, 1][f][x, y]}

grad[f][1, 2]

{Derivative[1, 0][f][1, 2], Derivative[0, 1][f][1, 2]}

grad[{f, g}][x, y]

{{Derivative[1, 0][f][x, y], Derivative[0, 1][f][x, y]}, 
   {Derivative[1, 0][g][x, y], Derivative[0, 1][g][x, y]}}

grad[{{f, g}, {h, i}}][x, y]

{{{Derivative[1, 0][f][x, y], Derivative[0, 1][f][x, y]}, 
     {Derivative[1, 0][g][x, y], Derivative[0, 1][g][x, y]}}, 
   {{Derivative[1, 0][h][x, y], Derivative[0, 1][h][x, y]}, 
     {Derivative[1, 0][i][x, y], Derivative[0, 1][i][x, y]}}}


Bob Hanlon

---- Sam Takoy <sam.takoy at yahoo.com> wrote: 

=============
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...



  • Prev by Date: Re: More universal way of writing gradient
  • Next by Date: Re: How to apply a list of functions
  • Previous by thread: Re: More universal way of writing gradient
  • Next by thread: Re: What assumptions to use to check for orthogonality