# Can I Simplify the Gradient of an If Statement?

Posted 9 years ago
1983 Views
|
3 Replies
|
0 Total Likes
|
 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?
3 Replies
Sort By:
Posted 9 years ago
 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]]] 
Posted 9 years ago
 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}] 
Posted 9 years ago
 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 ...