fkampas
(Frank Kampas)
September 15, 2014, 7:14pm
1
As an example, if I calculate the gradient of an If statement in the following way:
grad = Grad[If[x^2 + y^2 >= 1, x^2 + y^2, x + y + .5], {x, y}]
I get
{If[x^2 + y^2 >= 1, 2 x, 1], If[x^2 + y^2 >= 1, 2 y, 1]}
I’d like to have a general method to convert the gradient to the equivalent, but simpler
If[x^2 + y^2 >= 1, {2 x, 2 y}, {1, 1}]
Is there a general way to do that?
sukrause
(Udo Krause)
September 15, 2014, 8:29pm
2
You can
In[42]:= Clear[kampasGrad]
kampasGrad[expr_] := Grad[expr, {x, y}]
In[44]:= MapAt[Evaluate, MapAt[kampasGrad, If[x^2 + y^2 >= 1, x^2 + y^2, x + y + .5], {{2}, {3}}], {{2}, {3}}]
Out[44]= If[x^2 + y^2 >= 1, {2 x, 2 y}, {1, 1}]
it’s weak because kampasGrad should extract the independent variables on its own and because it overcomes the HoldRest of If with an extra MapAt, but as a first answer it might go here …
fkampas
(Frank Kampas)
September 15, 2014, 9:30pm
3
I wasn’t able to simplify the result of Grad acting on an If statement but I did come up with
myGrad[If[a_, b_, c_], vars_List] :=
If[a, Evaluate[Grad[{b, c}, vars]]]
sukrause
(Udo Krause)
September 17, 2014, 9:03pm
4
With a piecewise function it is
Apply[{Grad[#1, Variables[#1]], #2} &, Piecewise[{{x^2 + y^2, x^2 + y^2 >= 1}, {x + y + 1/2, x^2 + y^2 < 1}}], {2}]