You can define a function that evaluates to the needed piecewise function while evaluating it.
f[x_] := E^x
fp[foo_, x_, k_Integer?Positive, j_Integer?Positive] /; j <= k 2^k :=
Piecewise[{
{(j - 1)/(2^k), (j - 1)/(2^k) <= foo[x] <= j/(2^k)},
{k, foo[x] >= k}
}]
fp
creates the Piecewise
function series item for a k
and j
. It checks that j
and k
are integers with the addition of checking that j
is in the correct range. When fp
is called it both builds the function and evaluates it.
fp[f, 0.5, 2, #] & /@ Range[2 2^2]
(* {0, 0, 0, 0, 0, 0, 3/2, 0} *)
With Table
we can generate the set of Piecewise
functions for a particular k
.
With[{k = 1}, Table[fp[f, x, k, j], {j, k 2^k}]]
(*
{Piecewise[{{0, 0 <= E^x <= 1/2}, {1, E^x >= 1}}, 0],
Piecewise[{{1/2, 1/2 <= E^x <= 1}, {1, E^x >= 1}}, 0]}
*)
This can be used in Plot
to show the set of functions.
plotIt[foo_, k_Integer?Positive] :=
Plot[Evaluate@Table[fp[foo, x, k, j], {j, 2^k k}], {x, -2, 2},
PlotStyle -> (ColorData["SolarColors"][#] & /@ Rescale@Range[2^k k])]
The Evaluate
is needed because of Plot
s HoldAll
attribute.
plotIt[f, 3]
Of course you know you need to take some care with parameter k
in plotIt
as the sequence of gets very long for small k
. You can help mitigate this with the PlotPoints
option.
Hope this helps.
Update
Plotting performance for larger k
can be greatly increased by plotting each piecewise function individually and spreading the plots over the available kernels in parallel. parallelPlotIt
does this and significantly reduces the plot time.
parallelPlotIt[foo_, k_Integer?Positive] :=
Module[{fpList, colors, mapList, plots},
fpList = Table[fp[foo, x, k, j], {j, 2^k k}];
colors = ColorData["SolarColors"][#] & /@ Rescale@Range[2^k k];
mapList = Transpose@{fpList, colors};
plots =
ParallelMap[
Plot[#[[1]], {x, -2, 2}, PlotStyle -> #[[2]],
PlotRange -> {Full, {0, Automatic}}] &, mapList, 1];
Show[plots]
]
The plots and their plot style are paired up in mapList
before ParallelMap
is used to spread the plotting over the kernels. The plot range of each has been tweaked a bit as it was going negative on the y-axis for some reason.