环境: mathematica 12.0, fedora 29 workstation x86_64
smooth L1:
f
(
x
)
=
{
0.5
x
2
∣
x
∣
<
1
∣
x
∣
−
0.5
otherwise
f(x)= \begin{cases} 0.5x^2 & \mid x\mid<1\\ \mid x\mid-0.5 & \text{otherwise} \end{cases}
f(x)={0.5x2∣x∣−0.5∣x∣<1otherwise
f = Piecewise[{{0.5 #^2, Abs[#] < 1}, {Abs[#] - 0.5, Abs[#] >= 1}, {Log[#], 2 < #}}] &;
colorFunction = f;
piecewiseParts = Length@colorFunction[[1, 1]];
colors = ColorData[1][#] & /@ Range@piecewiseParts;
colorFunction[[1, 1, All, 1]] = colors;
Plot[f[x], {x, -2, 2}, ColorFunction -> colorFunction, ColorFunctionScaling -> False]
code snipet 2:
pwSplit[_[pairs : {{_, _} ..}]] :=
Piecewise[{#}, Indeterminate] & /@ pairs
pwSplit[_[pairs : {{_, _} ..}, expr_]] :=
Append[pwSplit@{pairs}, pwSplit@{{{expr, Nor @@ pairs[[All, 2]]}}}]
pw = Piecewise[{{0.5 x^2, Abs[x] < 1}, {Abs[x] - 0.5, Abs[x] >= 1}}];
Plot[Evaluate[pwSplit@pw], {x, -2, 2}, PlotStyle -> Thick, Axes -> True]
[1] https://mathematica.stackexchange.com/questions/1128/plotting-piecewise-function-with-distinct-colors-in-each-section