34 views (last 30 days)

What is the proper way to compute effectively (fast) the expected value E(x) in a case when I have approximation of probability desity function f(x) by probability normalized histogram?

Is there (FEX) any code available?

the cyclist
on 22 Oct 2019

There might be some nuances in the numerical integration, but here is the basic idea. You need to approximate the integral of x over the pdf.

% For reproducibility

rng default

% Simulated data -- normal centered on x=5.

N = 1000000;

x = 5 + randn(N,1);

% Get the probability density function. (You have these values already?)

[pdf_x,xi] = ksdensity(x);

% The bin width. (In this case, they are all equal, so I just take the first one.)

dx = xi(2) - xi(1);

% Calculate the total probability. (It should be 1.)

total_probability = sum(pdf_x*dx)

% Calculate the mean, which is the expected value of x.

mean_x = sum(xi.*pdf_x*dx)

the cyclist
on 22 Oct 2019

The ksdensity was only for me to simulate something like what you probably had -- a discrete vector of locations and densitiies. You shouldn't need to do any smoothing, etc.

If you have irregular bin widths, all you need to do is the numerical integration of x * pdf * width, as I did.

Can you post your data?

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/486796-how-can-i-effectively-compute-expected-value-by-histogram-approximation-of-probability-desnsity-func#comment_759063

⋮## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/486796-how-can-i-effectively-compute-expected-value-by-histogram-approximation-of-probability-desnsity-func#comment_759063

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/486796-how-can-i-effectively-compute-expected-value-by-histogram-approximation-of-probability-desnsity-func#comment_759068

⋮## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/486796-how-can-i-effectively-compute-expected-value-by-histogram-approximation-of-probability-desnsity-func#comment_759068

Sign in to comment.