Custom lognormal fit function definition

Hi, I do not have the Statistics Toolbox, but I am trying to fit a lognormal distribution to my 1D data (D). The excerpt from my code is as follows (with all the sources):
% Variable definitions via http://en.wikipedia.org/wiki/Log-normal_distribution
m = mean(D);
v = var(D);
% Calculate fit variables
mu = log(m) - 0.5*(log(1 + v/m^2))
sigma = sqrt(log(1.0 + v/m^2))
% Function definition via http://mathworld.wolfram.com/LogNormalDistribution.html
lognormal_pdf = @(x)(1./(x*sigma*sqrt(2*pi))).*exp(-((log(x)-mu).^2)/(2*sigma^2));
% Fit data
x = 10:0.01:40;
y = lognormal_pdf(x);
I need to be sure that my code is correct and works the way I want it to. I do not have any means of verifying this. Could someone please help and point on any changes, if necessary? This is quite urgent so any help is greatly appreciated. Thanks!

Answers (1)

The code is incorrect if D is an array of 2 or more dimensions, as mean() would then likely be a vector, and using ^2 on a vector is an error ("inner matrix dimensions do not agree"). You would then also have the vector v matrix-divided by m^2, which would either give you dimension errors or results you really were not expecting.
What is your code going to do if the mean is 0? log(infinity) minus log(infinity) is going to be NaN.

3 Comments

I apologize that I was not clear in my question. D is a one dimensional array and the mean is not zero or infinity (NaN) for my dataset. Given that D is a 1D array, would you say the code is will give the desired result?
Presumably the hints in the other post didn't do it for you, and you still need more hints: http://www.mathworks.com/matlabcentral/answers/14537-log-normal-distribution-fitting
Indeed, I checked the post you are referring to before posting my own code here. What I want is to confirm that my code gives the desired results, i.e., the nuts and bolts of the fitting routine in matlab rather than the procedure of how to go about writing a fitting code.

Sign in to comment.

Categories

Products

Asked:

on 5 Oct 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!