4

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?

bbgodfrey
  • 61,439
  • 17
  • 89
  • 156

2 Answers2

5

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]}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • 1
    Or just {z1[t_], z2[t_]} = Piecewise[{{#, Sin[t] > Cos[t]}}] & /@ {Sin[t], Cos[t]}; Check definitions with Information /@ {z1, z2} – Bob Hanlon Sep 20 '15 at 05:42
2

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

ubpdqn
  • 60,617
  • 3
  • 59
  • 148