% TRIRND Generate numbers from a triangular distribution % % Density is f(x) = 2x for x in [0,1]. % function X=trirnd(m,n) if nargin<1, m=1; end if nargin<2, n=m; m=1; end % This may look like magic, but it is not. % We want random numbers X whose density is f(x)=2x, % so their cdf must be F(x)=x^2, by integration. % We first take uniformly distributed numbers U, % and apply the INVERSE FUNCTION of F, that is, square root. % The results will have cdf F as require. % This is the "inverse transform method" for generating % random numbers according to some desired distribution. % https://en.wikipedia.org/wiki/Inverse_transform_sampling U = unifrnd(0,1,m,n); X = sqrt(U);