2
$\begingroup$

I want to create a list of values from a piecewise function evaluated at points in a list. Is there a way to do this without using loops?

For example

z2 = Piecewise[{{x + y^2,x>3}},0]
z = z2/.{x->{1,2,3,4,5}, y->{4,6,3,1,2}}

I would like this to return

{0,0,0,5,9}

i.e.

{0,0,0,4 + 1^2, 5 + 2^2}.

If the function is not Piecewise this works as I expected (want).

I know I can loop over all the lists to do this, but I would like a more elegant solution if one exists.

$\endgroup$
2
  • 1
    $\begingroup$ Is this acceptable? z2[{x_, y_}] = Piecewise[{{x+y^2, x>3}}, 0]; z2/@Transpose[{{1,2,3,4,5},{4,6,3,1,2}}]] which gives you {0, 0, 0, 5, 9} $\endgroup$
    – Bill
    Commented Jul 3, 2018 at 5:39
  • $\begingroup$ Thanks Bill that worked. I went with the other option because I am using the function z2 for other things in the same notebook, and not having to make it explicit in x and y was useful (not that I mentioned that in my question). $\endgroup$
    – Esme_
    Commented Jul 3, 2018 at 6:44

3 Answers 3

1
$\begingroup$

You can use MapThread

MapThread[Function[{x, y}, Evaluate[z2]], {{1, 2, 3, 4, 5}, {4, 6, 3, 1, 2}}]

{0, 0, 0, 5, 9}

$\endgroup$
1
$\begingroup$

Update: No need to use MapThread or Thread if you make a Listable function from your z2 since, then, the function is automatically threaded over lists that appear as its arguments.

Function[{x, y}, Evaluate @ z2, Listable][{1, 2, 3, 4, 5}, {4, 6, 3, 1, 2}]

{0, 0, 0, 5, 9}

Alternatively, convert z2 to a function that is already Listable:

Simplify`PWToUnitStep[z2] /. {x -> {1, 2, 3, 4, 5},   y -> {4, 6, 3, 1, 2}}

{0, 0, 0, 5, 9}

or

Function[{x, y}, Evaluate@Simplify`PWToUnitStep[z2]][{1, 2, 3, 4, 5}, {4, 6, 3, 1, 2}]

{0, 0, 0, 5, 9}

Original answer:

z = z2 /. Thread[Thread /@ {x -> {1, 2, 3, 4, 5}, y -> {4, 6, 3, 1, 2}}]

{0, 0, 0, 5, 9}

Alternatively, define a function pw

pw = Piecewise[{{# + #2^2, # > 3}}, 0] &; (* or *)
pw = {x, y} \[Function] Piecewise[{{x + y^2, x > 3}}, 0];

and use it is as

pw @@@ Thread[{{1, 2, 3, 4, 5}, {4, 6, 3, 1, 2}}] (* or *)
Thread[Unevaluated[pw[{1, 2, 3, 4, 5}, {4, 6, 3, 1, 2}]]]

{0, 0, 0, 5, 9}

$\endgroup$
0
$\begingroup$

For some reason it works with the equivalent HeavisideTheta version, but not Piecewise.

z2 = HeavisideTheta[x - 3] (x + y^2)

z2 /. {x -> {1, 2, 3, 4, 5}, y -> {4, 6, 3, 1, 2}} /. HeavisideTheta[0] -> 0
(*{0, 0, 0, 5, 9}*)

Normally HeavisideTheta[0] is undefined, presumably so you can choose its behavior yourself, and in this case we need it to be zero. For the current case of x integers, we could have used UnitStep[x-4] without the extra Replace specification.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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