1
$\begingroup$

So I'd like to create a probability density function from an existing histogram from a program that I use. My input data is of the form

bin    hits
0.     0
0.025  0
0.05   0
0.075 15
0.1   97

etc.

and I imported it into Mathematica the following way

data

{{0.,0},{0.025,0},{0.05,0},{0.075,15},{0.1,97},...}

I want to read this data and create a probability density from it. The end goal is to then RandomVariate around this pdf:

pdf = HistogramDistribution[data, {bins[[1]], bins[[-1]], bwidth}]
new_data = RandomVariate[pdf,n]

My first attempt was to use HistogramDistribution to create a PDF from the imported Histogram - since this requires a set of data points, I attempted the following:

For[j = 1, j < Length[data] + 1, j++,
 For[k = 0, k < data[[j]][[2]], k++,
  AppendTo[temphisto, data[[j]][[1]]]
 ]
];

pdf = HistogramDistribution[temphisto, {bins[[1]], bins[[-1]], bwidth}];

Of course, this gets unnecessarily time consuming once I crank up the initial histogram entries and it also feels redundant to do so since I can achieve the output of HistogramList right from the start:

HistogramList[temphisto, {bins[[1]], bins[[-1]], bwidth}]

{{0.,0.025,0.05,0.075,0.1,...},
 {0,0,0,15,97,...}}

Is there a way to turn the output from HistogramList to a HistogramDistribution or maybe create a probability density function from an imported histogram?

Thanks for the aid!

$\endgroup$
1
$\begingroup$

Try WeightedData using the second column as weights vector:

SeedRandom[1]
data = Transpose[{Range[0, 1, .05], RandomInteger[50, 21]}];
data // TableForm // TeXForm

$\begin{array}{cc} 0. & 20 \\ 0.05 & 1 \\ 0.1 & 48 \\ 0.15 & 2 \\ 0.2 & 6 \\ 0.25 & 3 \\ 0.3 & 16 \\ 0.35 & 28 \\ 0.4 & 33 \\ 0.45 & 31 \\ 0.5 & 33 \\ 0.55 & 17 \\ 0.6 & 12 \\ 0.65 & 44 \\ 0.7 & 40 \\ 0.75 & 30 \\ 0.8 & 24 \\ 0.85 & 2 \\ 0.9 & 25 \\ 0.95 & 11 \\ 1. & 21 \\ \end{array}$

{bins, counts} = Transpose[data];
wd = WeightedData[bins, counts];
dist = HistogramDistribution[wd]

DataDistribution[<>,{21}]

SeedRandom[1]
RandomVariate[dist, 5]

{0.532869, 0.271123, 0.615577, 0.198003, 0.350237}

$\endgroup$
  • $\begingroup$ Thank you for your quick reply! I tried this and it works fine! It took me some time to figure out how to set the range in HistogramDistribution correctly, but I got it to work. $\endgroup$ – user46208 Jul 13 '18 at 10:17
  • $\begingroup$ @user46208, my pleasure. Thank you for the accept. Welcome to mma.se. $\endgroup$ – kglr Jul 13 '18 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.