4
$\begingroup$

I wrote this code:

Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}]

and I got its derivative with this code:

D[Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}], x]

But I need derivative just of function, and same distance, i.e.

Output

Any suggestion?

$\endgroup$

2 Answers 2

5
$\begingroup$
MapAt[D[#, x] &, Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}], {{1, ;; , 1}}]

Mathematica graphics

Note: this function works for expressions with Head Piecewise. For general expressions that contain Piecewise subexpressions, it can be used with ReplaceAll as follows:

Y[x_] = Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}]*F + 
   Piecewise[{{x^4, 0 <= x <= 3}, {x, x <= 6}}]*G;

Y[x] /. pw_Piecewise :> MapAt[D[#, {x, 2}] &, pw, {{1, ;; , 1}}]

Mathematica graphics

$\endgroup$
13
  • $\begingroup$ I need the same output in picture. For 0<=x<=1, (2x) $\endgroup$
    – bahram
    Apr 23, 2016 at 19:35
  • $\begingroup$ @ kglr If possible for you which describe about {1, ;; , 1}. And If I have Piecewise[{{x^2, 0 <= x <= 1}, {x, 1 <= x <= 4}, {x, 4 <= x <= 5}}] this code is correct, too. $\endgroup$
    – bahram
    Apr 24, 2016 at 13:44
  • $\begingroup$ @bahram, {{i,j,k}} refers to the part {i,j,k}, i.e., "the k th part of the _ j_ th part of i th part" of the object in the second argument of MapAt. ;; is the same as All. For pw= Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}], you can inspect pw[[1]], pw[[1,2]], pw[[1, 2,1]], pw[[1, ;;,1]] or pw[[1,All,1]] etc to see the parts. Replacing the second argument in MapAt with Piecewise[{{x^2, 0 <= x <= 1}, {x, 1 <= x <= 4}, {x, 4 <= x <= 5}}] you should get a similar result. $\endgroup$
    – kglr
    Apr 24, 2016 at 14:00
  • $\begingroup$ @ kglr Many many thanks. $\endgroup$
    – bahram
    Apr 24, 2016 at 14:52
  • $\begingroup$ Excuse me, for end comment, what is high order derivative of pw in this code? (For example: D[pw, {t, 3}]). $\endgroup$
    – bahram
    Apr 24, 2016 at 15:12
1
$\begingroup$

Using an undocumented function,

Piecewise[Transpose[Reverse[MapAt[D[#, x] &, 
          Internal`FromPiecewise[Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}]], 2]]]]
   Piecewise[{{2 x, 0 <= x <= 1}, {1, x <= 4}}, 0]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.