Update 2: Using WeightedData, EmpiricalDistribution, Randomvariate
ClearAll[wdF]
wdF[t_, v_, n_: 1] := Module[{d = EmpiricalDistribution[
WeightedData[v, Differences[Join[{0}, t, {1}]]]]},
RandomVariate[d, n]]
Examples:
thresholds = {.1, .2, .34};
values = {1, 3, 19.1, 7.7};
wdF[thresholds, values]
(* {7.7} *)
wdF[thresholds, values, 10]
(* {1, 7.7, 19.1, 7.7, 7.7, 7.7, 7.7, 19.1, 19.1, 1} *)
Update: Folding Ifs
ClearAll[foldedIf]
foldedIf[t_, v_][x_] := Module[{args =
Reverse@Thread[{Partition[Join[{-∞}, t], 2, 1], Most@v}]},
Fold[If[# <= x < #2 & @@ #2[[1]], Evaluate@Last@#2, #] &, Last@v, args]]
Examples:
foldedIf[{t1, t2, t3}, {a, b, c, d}][x]
If[-∞ <= x < t1, a, If[t1 <= x < t2, b, If[t2 <= x < t3, c, d]]]
foldedIf[thresholds, values][w]
If[-∞ <= w < 0.1, 1, If[0.1 <= w < 0.2, 3, If[0.2 <= w < 0.34, 19.1, 7.7]]]
foldedIf[thresholds, values] /@ RandomReal[1, 5]
(* {7.7, 7.7, 19.1, 7.7, 7.7} *)
Two-argument form of Fold:
ClearAll[feldIf]
feldIf[t_, v_][x_] := Fold[If[# <= x < #2 & @@ #2[[1]], Evaluate@Last@#2, #] &,
Prepend[Reverse@ Thread[{Partition[Join[{-∞}, t], 2, 1], Most@v}], Last@v]]
feldIf[{t1, t2, t3}, {a, b, c, d}][x]
If[-∞ <= x < t1, a, If[t1 <= x < t2, b, If[t2 <= x < t3, c, d]]]
Original post:
y := With[{rr = RandomReal[]},
Piecewise[{{1, rr < .1}, {3, .1 <= rr < .2}, {19.1, .2 <= rr < .34}}, 7.7]]
Table[y, {10}]
(* {7.7`, 3, 7.7`, 3, 19.1`, 7.7`, 7.7`, 7.7`, 19.1`, 7.7`} *)
A function that constructs a Piecewise function given a list of thresholds and a list of values:
ClearAll[pwF]
pwF[t_, v_][x_] := Module[{args = Join @@@
Thread[{List /@ v, Partition[Join[{0}, t, {Infinity}], 2, 1]}]},
Piecewise[{#, #2 <= x < #3} & @@@ args]]
Example:
thresholds = {.1, .2, .34};
values = {1, 3, 19.1, 7.7};
pwF[thresholds, values]@x

pwF[thresholds, values] /@ RandomReal[1, 10]
(* {7.7`, 19.1`, 7.7`, 19.1`, 3, 7.7`, 1, 19.1`, 19.1`, 7.7`} *)
Which. – bbgodfrey Apr 21 '15 at 00:36