MATLAB: Fitting lognaormal distribution with constraints

lognormalStatistics and Machine Learning Toolboxstats

I am trying to fit a lognormal dostribution to a dataset, I wish to constrain the 95th and 99th percentile. Is there a way to do this in Matlab?
Sorry if this is obvious buit i am a new user

Best Answer

The lognormal distribution has two parameters (mu & sigma). If you impose two constraints (namely that the fitted distribution has to have the same 95th and 99th percentile values), then you've determined your parameters. So you're not really fitting the data and constraining the percentiles -- you're fitting the data by constraining the percentiles.
That doesn't sound like a particularly safe thing to do, when the constraints are -- by definition -- outliers, but I'm no statistical guru, so...
Assuming that's really what you want to do:
% Create some data
w = random('lognormal',4.5,0.25,[100 1]);
% Get the empirical quantiles
q1 = quantile(w,0.95);
q2 = quantile(w,0.99);
% Define function to minimize
f = @(p) norm([logninv(0.99,p(1),p(2))-q2;logninv(0.95,p(1),p(2))-q1]);
% Get parameters for MLE fit
pmle = lognfit(w)
% Use them as a starting point for constrained fit
pcon = fminsearch(f,pmle)
% View results
ww = linspace(0,200,501);
ymle = logncdf(ww,pmle(1),pmle(2));
ycon = logncdf(ww,pcon(1),pcon(2));
plot(ww,ymle,ww,ycon,q1,0.95,'o',q2,0.99,'o')
You should see that the two percentile points in the resulting graph lie on the green curve, but probably not on the blue curve. The blue is the unconstrained fit, from lognfit; the green is from forcing the cdf to go through the empirical quantiles.
pmle is a vector of mu and sigma from a regular MLE fit; pcon is a vector of the parameters from the constrained fit.