Message Boards Message Boards

0
|
2155 Views
|
3 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Can I Simplify the Gradient of an If Statement?

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?

POSTED BY: Frank Kampas
3 Replies

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 BY: Frank Kampas

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 BY: Udo Krause

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

POSTED BY: Udo Krause
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract