Leader

Monday 25 May 2015

Alternative function: Normal cumulative density function (normcdf)

Download
normcdf2.m

Details
This function implements the basic functionality of the normcdf function in Matlab's stats toolbox. Similar to normcdf it takes three inputs, the x axis (x), mean of the distribution (mu) and the standard deviation (sigma) and generates a normal cumulative density function using the equation:

 y = 0.5*(1+erf((x-mu)/sqrt(2*sigma^2)))

See also normpdf2 for the equivalent probability density distribution.

Example

% Define parameters
mu = -1; % Mean
sigma = 0.5; % Standard deviation
x = -10:0.1:10; % x axis

% Generate curve
y1 = normcdf2(x, mu, sigma);
y2 = normcdf2(x, mu-1, sigma+2);
y3 = normcdf2(x, mu+6, sigma+0.5);

% Plot 
figure
plot(x, [y1', y2', y3'])
ylabel('Prob.')
xlabel('x')
legend({...
    ['mu=', num2str(mu), ', sigma=', num2str(sigma)], ...
    ['mu=', num2str(mu-1), ', sigma=', num2str(sigma+2)], ...
    ['mu=', num2str(mu+6), ', sigma=', num2str(sigma+1)], ...
    })




Code run-through
This is a really simple function. All it needs to do is handle the defining of the curve function and its evaluation using feval.

function y = normpdf2(x, mu, sigma)

The first line defines three inputs and one output. The input are the x axis (x), mean (mu) and standard deviation (sigma). The output is the generated curve (y).

f = @(u,o,x) 0.5*(1+erf((x-u)/sqrt(2*o^2)));

The mathematical function to generate normal probability density functions is defined and stored in the anonymous function f. An anonymous function is just a Matlab function that's stored in a variable in the workspace rather than a .m file. The @(u,o,x) part identifies it as a function with the (dummy) inputs uo and x, which represent musigma and x, respectively.

y = feval(f, mu, sigma, x);

Then feval is used to evaluate the function by passing the function handle (f, the variable storing the function) to feval along with the main functions parameters (musigmax) in the order specified in f's definition.

No comments:

AdSense