[Math] Matlab, finding the variance given a probability distribution

MATLABprobabilityrandom variablesstatistics

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$$

Best Answer

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.