# Matlab, finding the variance given a probability distribution

How would I numerically find the variance given a probability distribution in MATLAB? I understand(I think) how to do it symbolically, but is there any way to be confirm my results?

I am given the probability mass function, which is $$P(X=n)=2^{-n},\qquad n=1, 2, 3, \ldots$$

• What do you mean by "a function of the RV's probability distribution"? You should write explicitly what you are given. Mar 19, 2013 at 17:16
• I have reworded the entire question. Please check if it is OK. Sep 4, 2013 at 15:26
• do the analytical summation that you solved by hand using a truncated sum for $n = 1, 2, ..., 1000$ (for example) Sep 4, 2013 at 15:59

Use $f(x)$ to obtain a large sample of randomly generated variables $x_i$ which follow this distribution. In case of the normal distribution one could use s = normrnd(mu,sigma,n,m) to create such a sample. Given the vector $s$ containing the sample, you can calculate the variance by var(s). If $f(x)$ is difficult to sample from, you could use a rejection sampler.

Example: s = normrnd(0,1,1,10000) creates a large sample (n=10000) for $X\sim N(0,1)$. This gives var(s)=1.0053.

• Maybe I'm not understanding correctly, but how would one go from the probability distribution function to one in which I could obtain a large sample?
– John
Mar 19, 2013 at 17:20
• @John, it would help if you could give the specific distribution. If it's normal, binomial, etc. Matlab has built in functions to do this. Mar 19, 2013 at 17:23
• The distribution is 2^-n
– John
Mar 19, 2013 at 17:29
• So n is the random variable? What is the domain of the function? Mar 19, 2013 at 17:32
• P(X = n) = 2^-n, all pos. integers
– John
Mar 19, 2013 at 17:33

According to its definition the variance can be computed from the probability distribution function (BTW is it continuous or discrete, that is, is it a pdf or a pmf?) by integrating the 2nd power of the function minus its expected value. The wikipedia has the forumlas for both the continuous and discret case.

In the discrete case it would something like this: supposing you have the probabilities stored in p and the values in x, sum(p.*(x.^2))-sum(p.*x)^2. But I haven't checked this code.