# Are there any code which just derivative of piecewise function(same distence)?

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. Any suggestion?

## 2 Answers

MapAt[D[#, x] &, Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}], {{1, ;; , 1}}] 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}}] • I need the same output in picture. For 0<=x<=1, (2x) – bahram Apr 23 '16 at 19:35
• @ 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. – bahram Apr 24 '16 at 13:44
• @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[], 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. – kglr Apr 24 '16 at 14:00
• @ kglr Many many thanks. – bahram Apr 24 '16 at 14:52
• Excuse me, for end comment, what is high order derivative of pw in this code? (For example: D[pw, {t, 3}]). – bahram Apr 24 '16 at 15:12

Using an undocumented function,

Piecewise[Transpose[Reverse[MapAt[D[#, x] &,
InternalFromPiecewise[Piecewise[{{x^2, 0 <= x <= 1}, {x, x <= 4}}]], 2]]]]
Piecewise[{{2 x, 0 <= x <= 1}, {1, x <= 4}}, 0]
`