4
$\begingroup$

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)?

$\endgroup$
3
$\begingroup$

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}}

$\endgroup$
2
$\begingroup$

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} *)
$\endgroup$
  • $\begingroup$ 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). $\endgroup$ – Ponkadoodle Apr 14 '14 at 7:10

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.