1
$\begingroup$

Suppose I have a vector function

    f[x_] := {x[[1]]^2 - x[[2]]^2, Sin[x[[1]]] + Cos[x[[2]]]};

Then I want to make a list of gradients at some values:

    Grad[f[{x1, x2}], {x1, x2}] /. {{x1 -> 1, x2 -> 1}, {x1 -> -1, x2 -> 1}}
(* output: *)
{{{2, -2}, {Cos[1], -Sin[1]}}, {{-2, -2}, {Cos[1], -Sin[1]}}}

But for convenience I would like to wrap it with With like this:

    With[{x = {x1, x2}}, Grad[f[x], x] /. x -> {{1, 1}, {-1, 1}}]

But oops... something got wrong:

{{2 x1, -2 x2}, {Cos[x1], -Sin[x2]}}

What's wrong?

$\endgroup$
2
$\begingroup$

The problem is the rule you are trying to apply looks like this:

{x1, x2} -> {{1, 1}, {-1, 1}}

and of course {x1, x2} is not present in the expression.

Try this:

With[{x = {x1, x2}}, Grad[f@x, x] /. Thread[x -> #] & /@ {{1, 1}, {-1, 1}}]

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

$\endgroup$
  • $\begingroup$ Thanks, I like your answer. It's happen to be more obvious for me if is written in this way: Thread[Rule[x,#]]. Thread is cool function. $\endgroup$ – Dan Oak Nov 2 '14 at 17:00
  • $\begingroup$ BTW, I've seen your first variant Thread[x -> {{1, 1}, {-1, 1}}]]. We could also left it as it was and transpose the result. $\endgroup$ – Dan Oak Nov 2 '14 at 17:00
  • 2
    $\begingroup$ Perhaps an up-vote for @LinearLambda's answer is warranted since they provided the same solution, only without an explanation? (Just trying to look out for new users) $\endgroup$ – bobthechemist Nov 2 '14 at 17:12
  • $\begingroup$ good point @bobthechemist $\endgroup$ – mfvonh Nov 2 '14 at 17:13
2
$\begingroup$

For simplification you can also try to define a new function or use pure-function:

Evaluate@Grad[f[{#1, #2}], {#1, #2}] & @@@ {{1, 1}, {-1, 1}}
$\endgroup$
  • $\begingroup$ Thanks for interesting and different approach. I up-vote but not accept your answer since in my question I wanted to use With. However, I like your approach a lot. $\endgroup$ – Dan Oak Nov 2 '14 at 16:53
1
$\begingroup$

I don't understand exactly how it work but as the help say "With replaces symbols in expr only when they do not occur as local variables inside scoping constructs". So you should use rules on x1 and x2 like this

With[{x = {x1, x2}}, Grad[f[x], x] /. {x2 -> {1, 1}, x1 -> {-1, 1}}]
$\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.