4
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

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

$\endgroup$
5
$\begingroup$

You can use, for example

Refine[Piecewise[{{x^2, x < 0}, {x, x > 0}}], x < 0]
$\endgroup$
1
$\begingroup$
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

$\endgroup$
0
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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