# Weibull distribution: from mean and variance to shape and scale factor

I need to sample values from a Weibull distribution whose mean and variance are provided (respectively 62 and 4275). I am running a Matlab code, therefore if I want to use wblrnd(shape,scale) I need to estimate these two parameters. The problem is that,according to wikipedia, mean and variance are related to shape and scale parameters via a gamma function, and this makes the calculation non-trivial. Is there a simple way to sample values in Matlab via mean and variance, or to easily move from these two parameters to the shape and scale parameters?

This can be accomplished with monovariate root finding. First solve for the shape parameter, $\lambda$, in terms of the scale parameter, $k$, using the expression for the mean, $\mu$, of the standard Weibull distribution:

$$\mu = \lambda \Gamma\left(1+\frac{1}{k}\right) \rightarrow \lambda = \frac{\mu}{\Gamma\left(1+\frac{1}{k}\right)}$$

Then plug this in to the expression for the variance, $\sigma^2$, to eliminate $\lambda$ and simplify:

$$\sigma^2 = \lambda^2 \left(\Gamma\left(1+\frac{2}{k}\right) - \left(\Gamma\left(1+\frac{1}{k}\right)\right)^2\right) \rightarrow \frac{\sigma^2}{\mu^2} - \frac{\Gamma\left(1+\frac{2}{k}\right)}{\left(\Gamma\left(1+\frac{1}{k}\right)\right)^2} + 1 = 0$$

This appears to be a monotonically increasing function for $k \in (0,+\infty)$ and the specified values of $\mu$ and $\sigma^2$. The root of this function can be found in Matlab by using fzero:

mu = 62;
sig2 = 4275;
f = @(k)sig2/mu^2-gamma(1+2./k)./gamma(1+1./k).^2+1;
k0 = 1;               % Initial guess
k = fzero(f,k0)       % Solve for k
lam = mu/gamma(1+1/k) % Substitue to find lambda


which yields

k =

0.948647322786540

lam =

60.540561349132474


You can then verify that this works by sampling with wblrnd:

rng(1); % Set seed to make repeatable
n = 1e7;
r = wblrnd(lam,k,[n 1]);
mu_r = mean(r)
sig2_r = var(r)