Re: Creating a Piecewise function with imported list of arbitrary length
- To: mathgroup at smc.vnet.net
- Subject: [mg128977] Re: Creating a Piecewise function with imported list of arbitrary length
- From: Ray Koopman <koopman at sfu.ca>
- Date: Thu, 6 Dec 2012 05:00:33 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
- References: <k9kek2$681$1@smc.vnet.net>
On Dec 4, 1:09 am, Nick Broderick <crazychess... at msn.com> wrote:
> Apologies if this seems like a simple question, but I'm not
> familiar enough with Mathematica syntax to know how to do this.
> Essentially I have an arbitrary list (length n) of pairs -- taken
> from an input file -- from which I need to define a Piecewise
> function. The pairs (x_i,y_i) define the left-sided endpoints
> for each portion of the function, and the last point defines
> the value y_n of the function for x > x_n. For example:
>
> {{0,1},{300,2},{600,3}}
>
> defines a Piecewise function:
>
> f(x)= {{1, 0 <= x <300},{2, 300 <= x <600}, {3, x > 600}, {0, True}}
>
> But I'm not sure how to go about creating a arbitrary list of
> conditions from my list of pairs. Any help would be appreciated.
Here's another version, that I think is a little easier
to follow. In general, I use Apply (@@ and @@@) instead
of Map (/@) whenever it will let me use numbered arguments
instead of indexed arguments; e.g., #2 instead of #[[2]].
f[x_] = Piecewise @ Append[
{#2, #1 <= x < #3}& @@@ Partition[Flatten@data,3,2],
{#2, x >= #1}& @@ Last@data]