2
$\begingroup$

I have a piecewise function and I'm trying to extract the different functions for different values of the parameter. I use:

First/@(InitialEnvelope[\[Beta]]//PiecewiseExpand)[[1]]

This gives be back the different functions except the last piece which is the function when the else or True condition holds. How can I extract the function at True?

$\endgroup$
3
$\begingroup$

In Mathematica everything is specified via patterns. So are, of course, Piecewise functions. To obtain a standardized form for nested Piecewise functions you were right to apply PiecewiseExpand first. So let's take a look at an example of a nested Piecewise function:

(*definition*)
pw = Piecewise[{{g[x],x > 5}, {Piecewise[{{h1[x],x < 1}, 
{h2[x],x > 2}}, h3[x]], x < 3}}, f[x]];
(*expansion*)
pwe = PiecewiseExpand[pw];

Remember my remark about patterns before. Let's take a look at the underlying pattern (form) of the expanded Piecewise function:

pwe // FullForm

This gives you a clue on how to extract all the functions via using the Part operator, here is one possibility to do it:

Flatten[{pwe[[1, ;; , 1]], pwe[[2]]}]

{f[x], g[x], h1[x], h2[x], h3[x]}

Have fun playing around with this.

$\endgroup$
  • $\begingroup$ Thank you. I also tried to do it with Union, but it takes more time than Flatten. Any idea why? $\endgroup$ – Rby Sep 17 '16 at 14:21
  • $\begingroup$ Union should be slower because it creates a new object, while Flatten does not do that. Also important to note is that according to Mathematica help Union "gives a sorted list of all the distinct elements", so additional sorting is applied, which costs time. For lists containing only a few elements you should not really notice a difference, of course this looks different for large lists. $\endgroup$ – Wizard Sep 17 '16 at 14:28

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.