3
$\begingroup$

I have a calculation that outputs a piecewise function that has as its cases a list of expressions. An example (3 cases with each a list of 4 expressions) is below:

pw[x_,y_]:=Piecewise[{{{a1,b1,c1,d1},x>5y},{{a2,b2,c2,d2},x<3y}},{a3,b3,c3,d3}]

I need to remove the first expression (a1 or a2 or a3) before use in further calculation, so I apply the following Delete operations.

pw2[x_,y_]:=pw[x,y]//Delete[#,Table[{1,i,1,1},{i,1,Length[#[[1]]]}]]&//Delete[#,{2,1}]&
pw2[w,v] (*evaluates correctly*)
pw2[1,2] (*fails because it is no longer piecewise when evaluated*)

The above pw2[w,v] gives the desired output, but I would like the function to handle both symbolic inputs and numbers, but pw2[1,2] fails since the deletions are not being applied to a piecewise function.

While I might be able to use Hold or Block. I thought this case should be simple enough to be handled separately without imposing a hold on large parts of the calculation.

Attempted Fix 1: If statement

(*Try if statement to handle when inputs are symbolic and when they are numbers*)
pw3[x_,y_]:=If[VectorQ[{x,y}], pw[x,y]//Delete[#,1]&, pw2[x,y]]
pw3[w,v] (*fails for some reason related to the conditions of the piecewise functions being erased?*)
pw3[1,2] (*works as desired*)

The If statement approach seems to break the piecewise function. Why does this happen in a seemingly innocuous If statement? I had encountered similar errors with Piecewise when testing the Delete in pw2.

I though this might just be because If is a programmic construct, so I should use a mathematical construct.

Attempted Fix 2: Piecewise function

(*Try piecewise function to handle cases*)
pw4[x_,y_]:=Piecewise[{{pw[x,y]//Delete[#,1]&,VectorQ[{x,y}]}},{pw2[x,y]}]
pw4[w,v] (*fails as in pw3*)
pw4[1,2] (*works as desired*)

This has the same errors as in the If statement case.

What is happening in piecewise that causes the above to fail?

$\endgroup$

1 Answer 1

3
$\begingroup$

Inject x and y after the deletions are done on p[.,.]:

ClearAll[pw2]
pw2[x_, y_] := (pw[\[FormalX], \[FormalY]] // 
     Delete[#, Table[{1, i, 1, 1}, {i, 1, Length[#[[1]]]}]] & // 
    Delete[#, {2, 1}] &) /. {\[FormalX] -> x, \[FormalY] -> y}

pw2[w, v] 

enter image description here

pw2[1, 2]

{b2, c2, d2}

An alternative way to get the same result:

ClearAll[pw23]
pw3[x_, y_] := Replace[pw[x, y], {a_, b_, c_, d_} :> {b, c, d}, All]

pw3[w, v] 

enter image description here

pw3[1, 2]

{b2, c2, d2}

$\endgroup$

Your Answer

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

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