# Piecewise function using Quantity is returning a Piecewise answer

i[t_] = Piecewise[{{Subscript[I, 1]/Subscript[t, 1] t,
Quantity[0, "Seconds"] < t <= Subscript[t, 1]}, {Subscript[I, 1],
Subscript[t, 1] < t < Subscript[t, 2]}, {Subscript[I, 1] -
Subscript[I, 1]/(
Subscript[t, 4] - Subscript[t, 3]) (t - Subscript[t, 2]),
Subscript[t, 2] <= t <= Subscript[t, 4]}}, Quantity[0, "Amperes"]]

When I run this function and try an input like

i[Quantity[3, "Seconds"]]

• You can't use I as a variable because Mathematica reads it as Complex[0,1] or Sqrt[-1] Commented Aug 19, 2016 at 18:43
• You can if it has an underscore. At least, it's been working like that for me for all my other problems. Commented Aug 19, 2016 at 18:53
• Your troubles are almost assuredly caused by your use of Subscript. The function returns a piecewise result because it cannot determine which right hand side is True. What is definition of $t_1$ for example?
– chuy
Commented Aug 19, 2016 at 20:47

Using the function definitions from your answer and setting t to 3 seconds

i[Quantity[3, "Seconds"]]

produces

Note that the solution using subscripts is taking QuantityMagnitude[Subscript[t, 1]] and setting it equal to "3 Seconds" (i.e., the input value of t) with a subscript of 1!! The same happens to all of the other t with subscripts.

I don't think that is what you had in mind (was it?).

Below is a definition that doesn't use subscripts (the folks here are trying to help you by indicating that using subscripts as symbols is a road to disaster). Also you are looking for trouble if you use I rather i as a variable.

iN[t_] := Piecewise[
{
{i1/t1 Quantity[t, "Seconds"], 0 < t <= QuantityMagnitude[t1]},
{current, t < QuantityMagnitude[t2]}
},
i1 - i1/(t4 - t3) (Quantity[t, "Seconds"] - t2)
]

Using iN with t set to 3 seconds

iN[Quantity[3, "Seconds"]]

produces

I couldn't get it to work as one function, but I found a workaround using multiple functions.

Subscript[i, 1][t_] =
Subscript[I, 1]/Subscript[t, 1] Quantity[t, "Seconds"];
Subscript[i, 2][t_] =
Subscript[I, 1] - Subscript[I, 1]/(
Subscript[t, 4] - Subscript[t,
3]) (Quantity[t, "Seconds"] - Subscript[t, 2]);

i[t_] = Piecewise[{{Subscript[i, 1][t],
0 < t <= QuantityMagnitude[Subscript[t, 1]]}, {Subscript[current,
1], t < QuantityMagnitude[Subscript[t, 2]]}}, Subscript[i, 2][t]];