A rule replacement problem: list -> list

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?

=================

=================

3 Answers
3

=================

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]}}}

  

 

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.
– dahn oak
Nov 2 ’14 at 17:00

  

 

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.
– dahn oak
Nov 2 ’14 at 17:00

2

 

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)
– bobthechemist
Nov 2 ’14 at 17:12

  

 

good point @bobthechemist
– mfvonh
Nov 2 ’14 at 17:13

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}}

  

 

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.
– dahn oak
Nov 2 ’14 at 16:53

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}}]