# How can I generate half-normal variates in MATLAB?

I can find the

random('normal', 0, 1, 10000,1)


command in MATLAB but it generates half-normal variates. I would like to generate random half-normal variates. The half-normal distribution is defined by

$$f_{|Z|}(x)=\frac{2}{\sqrt{2\pi}}e^\frac{-x^{2}}{2}.$$

Can I generate a random half-normal variates from random normal variates?

• Recommend adding "Truncate" or "Truncation" tag. – SecretAgentMan Sep 26 '18 at 4:23
• @SecretAgentMan I don't think those tags (neither truncation nor normal-distribution) would increase the content visibility and improve the question on CompSci SE. – Anton Menshov Sep 26 '18 at 4:27

## 2 Answers

As Wikipedia says, you can just compute a normally distributed random variable with a mean of zero and take the absolute value. The half-normal probability distribution function is identical to the normal PDF with $\mu = 0$ for $X > 0$, except for a factor of two for the normalization.

If $$X\sim \text{Normal}(\mu,\sigma)$$, then the $$Y\sim \text{Half-Normal}$$ is obtainable via several approaches.

1. Absolute Value: $$\quad Y = |X|\quad$$ (As pointed out by @DavidZ.)
2. Truncation: $$\quad Y = X_{(0,\infty)} \quad$$ MATLAB does this nicely with truncate().
3. Conditioning (Logical Indexing): $$\quad Y = (X|X>0)\quad$$

Graphical examples below with code.

% MATLAB R2018b
mu = 0; sigma = 1;
pdN = makedist('Normal',mu,sigma);
pdHN = truncate(pdN,0,inf);

X = (-4:.01:4)';
Xt = X(X>0);

figure, hold on, box on
p(1) = plot(X,pdf(pdN,X),'k-','DisplayName','Normal')
p(2) = plot(Xt,pdf(pdHN,Xt),'b-','DisplayName','HalfNormal')
YAxis = get(gca,'YTick');
plot([0;0],[0,YAxis(end)],'b--','HandleVisibility','off')
legend('show')
set(p,'LineWidth',1.8)
ylabel('Probability Density Function (PDF)')


Y = random(pdN,50000,1);
Yt = Y(Y>0);

figure, hold on, box on
histogram(Y,'Normalization','pdf','FaceColor','k','DisplayName','Normal')
histogram(Yt,'Normalization','pdf','FaceColor','b','DisplayName','HalfNormal')
legend('show')