5

For example, if I have Piecewise[{{x^2, x < 0}, {x, x > 0}}], how do I select only the function that is for x < 0? I want to set a new function equal to the x^2 only, not the entire piecewise function.

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
mikal94305
  • 153
  • 4

4 Answers4

7

You can use, for example

Refine[Piecewise[{{x^2, x < 0}, {x, x > 0}}], x < 0]
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
5

As you may know, Part ([[ ]]) works on non-lists as well. So, you can index your Piecewise like so:

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

x^2

With Cases you can pick out the part with a specific condition:

Cases[Piecewise[{{x^2, x < 0}, {x, x > 0}}], {a_, x < 0} -> a, {2}] // First

x^2

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
1

As mentioned by @'Sjoerd C. de Vries', you can use

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

For the first and select left elements. Surprisingly, if you wanted the third however, P[[1,3,1]] won't work, and you will need instead:

 P[[2]]

This was actually discussed in this post

Matifou
  • 175
  • 1
  • 8
1
ClearAll[pwPick]
pwPick = Module[{fpw = Internal`FromPiecewise @ #, cond = #2}, 
   First @ Pick[fpw[[2]], # === cond & /@ fpw[[1]]]] &

Examples:

pw = Piecewise[{{x^2, x < 0}, {x, x > 0}}];
pwPick[pw, x < 0]

x^2

pwPick[pw, x > 0]

x

pwPick[pw, True]

0

kglr
  • 394,356
  • 18
  • 477
  • 896