4
$\begingroup$

It sometimes is useful to combine such expressions as

z1[t_] = Piecewise[{{Sin[t], Sin[t] > Cos[t]}}]
z2[t_] = Piecewise[{{Cos[t], Sin[t] > Cos[t]}}]

into something like

{z1[t_], z2[t_]} = Piecewise[{{{Sin[t], Cos[t]}, Sin[t] > Cos[t]}}]

especially when the List of zi is large, and the Piecewise conditions are many and expensive to evaluate. However, the expression immediately above yields the error message

Set::shape: Lists {z1[t_],z2[t_]} and Piecewise[{{{Sin[t], Cos[t]}, Sin[t] > Cos[t]}}, 0] are not the same shape. >>

(The same error occurs with Set replaced by SetDelayed and for similar If statements.)

The following does work but seems cumbersome.

{z1[t_], z2[t_]} = Module[{tst = Sin[t] > Cos[t]}, 
    {Piecewise[{{Sin[t], tst}}], Piecewise[{{Cos[t], tst}}]}]

Is there a better approach that is extendable to a large number of zi and Piecewise conditions?

$\endgroup$
5
$\begingroup$

If your goal is to reduce typing, you could try something like

{z1[t_], z2[t_]} =
  With[{u = Sin[t] > Cos[t]}, Piecewise[{{#, u}}]]& /@ {Sin[t], Cos[t]};

This gives

{z1[t], z2[t]}
{Piecewise[{{Sin[t], Sin[t] > Cos[t]}}, 0], Piecewise[{{Cos[t], Sin[t] > Cos[t]}}, 0]}
$\endgroup$
  • 1
    $\begingroup$ Or just {z1[t_], z2[t_]} = Piecewise[{{#, Sin[t] > Cos[t]}}] & /@ {Sin[t], Cos[t]}; Check definitions with Information /@ {z1, z2} $\endgroup$ – Bob Hanlon Sep 20 '15 at 5:42
2
$\begingroup$

I am not sure what the aim is but you could also:

f[t_] := Piecewise[{{{Cos[t], Sin[t]}, Sin[t] > Cos[t]}, {{0, 0}, 
    True}}]

Plotting:

ParametricPlot[Evaluate[f[t]], {t, 0, 2 Pi}, Exclusions -> None]

enter image description here

$\endgroup$

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.