2
$\begingroup$

I want to define a function for finding a Jacobian matrix of pure vector function of vector argument. I try

J[Function[vars_List /; VectorQ[vars], funs_]] := Function @@ Evaluate /@ {vars, D[funs, {vars}]}

A = Function[{x, y, \[Theta], v, \[Omega]}, {v Cos[\[Theta]], v Sin[\[Theta]], \[Omega], 0, 0}]

J[A]

, this code works great but I get Function::flpar message.

Is it possible to achieve same result correctly?

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$ – bbgodfrey Feb 25 '15 at 13:58
2
$\begingroup$

There are a few issues with your code. A minimal change to make it work would be:

ClearAll[J];
J[HoldPattern[Function[vars_List /; VectorQ[vars], funs_]]] := 
   Function @@ Evaluate /@ {vars, D[funs, {vars}]}

The reason you need HoldPattern has to do with how lhs. of assignment is evaluated during the assignments.

However, this is not all. The code as it stands has problems in the form of evaluation leaks, particularly when the variables have global values. A safer version of the code would be:

ClearAll[J];
J[HoldPattern[Function[vars_List /; VectorQ[Unevaluated[vars]], body_]]] := 
   Block[vars, Function @@ {vars, D[body, {vars}]}]

where I used Unevaluated to prevent evaluation of vars during pattern-matching, Block to prevent evaluation of vars during function construction on the r.h.s., and removed Evaluate, which isn't needed. Note also that, while I left your VectorQ test for didactic purposes, it isn't needed either, because you already test that the arguments are in a list.

Personally I'd use yet different code:

ClearAll[J];
J[HoldPattern[Function[vars : {__Symbol}, body_]]] :=
   Block[vars, Function @@ {vars, D[body, {vars}]}]

which is simpler and avoids some of the problems of the previous versions, while being yet more robust.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.