Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

In mathematica, I have a piecewise function similar to:

Piecewise[{ {x^2 + 2*x - 4, 0 <= x <= 1/4},
            {0, true}                    }]

I don't know how many pieces there will be, or what the internal ordering will look like, but I know that exactly one of the pieces will have x=0 as its left endpoint. How do I extract that piece in its general form (x^2 + 2*x - 4) without knowing the upper end of its domain (1/4)?

share|improve this question

migrated from math.stackexchange.com Apr 11 at 11:06

This question came from our site for people studying math at any level and professionals in related fields.

2 Answers 2

up vote 3 down vote accepted

Given say:

expr = Piecewise[{ {x^2 + 2*x - 4, 0 <= x <= 2}, 
                   {0, True}}]

... you can convert your Piecewise expression back into a list form using:

 aa = Internal`FromPiecewise[expr, True]  // Transpose

{{x >= 0 && x <= 2, -4 + 2 x + x^2}, {x > 2 || x < 0, 0}}

Then, you can find the part that corresponds to x == 0 using:

Select[aa, (#[[1]] /. x -> 0) &]

{{x >= 0 && x <= 2, -4 + 2 x + x^2}}

share|improve this answer

Similar to wolfies' approach - find the part for which the condition is True when x->0.

p = Piecewise[{{x^2 + 2*x - 4, 0 <= x <= 1/4}, {0, True}}];

Cases[First@p, {e_, c_} /; (c /. x -> 0) :> e]

(* {-4 + 2 x + x^2} *)
share|improve this answer
    
Thanks for the alternative approach! I'm accepting wolfies' answer mainly for the reason that it deals with the default case better than this one. For example, Piecewise[{{x^2 + 2*x - 4, 1 <= x <= 2}}] for x=0 gives {{x > 2 || x < 1, 0}} for wolfies' (indicating the default of 0), but {} for yours (making it a special case to handle). –  Wallacoloo Apr 14 at 7:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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