## Truncating exponentials in MATLAB

Exponential distributions are useful because waiting times (for example between stimuli) follow an exponential distribution.

Suppose we wish to produce 100 exponentially distributed random variables in the interval [Min, Max] with a given mean. (Min <= mean <= Max). Matlab code is given below to do this and illustrated with an example.

This is done in two stages. Firstly, compute m = (mean-min)/(max-min).

e.g. if min=100, max=200, mean=110 then m=0.1.

The below matlab code produces N=100 exponentially distributed random variables taking values between min=100 and max=200 with a mean of m. Run the code by pasting this syntax, with required N, min, max and m, replaced by its numerical value, obtained as described above, at a command prompt in matlab.

min=100; max=200; wout= inline('( (-exp(-x) ) / (1-exp(-x)) )*((x+1)/x) + 1/(x*(1-exp(-x)))- m',’x’); N=100; x = fzero(wout,1/m); rand('state',sum(100*clock)); s=rand(1,N); y = -log( 1- (1-exp(-x))*s )/x; rv = min + y*(max-min); hist(rv,(max-min)/10);

You can fit truncated regression models in R for example a truncated Normal distribution regression model can be fitted with the below code.

require(truncnorm) require(truncreg) x = (rtruncnorm(100, a = qnorm(.1, mean = 100, sd = 15), b=Inf, mean=100, sd=15)) sd(x) tr.mod = truncreg(x ~ 1, direction = "left", point = min(x)) confint(tr.mod)

Output:

[1] 13.34503 2.5 % 97.5 % (Intercept) 97.65863 106.46516 sigma 12.31238 18.93937

A 95% confidence interval for mean from this truncated Normal distribution can also be computed as below.

t.test(x)$conf.int

Output:

[1] 102.3069 107.6028 attr(,"conf.level") [1] 0.95