Leader

Monday 25 May 2015

Alternative function: Normal probability density function (normpdf)

Download
normpdf2.m

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

y = 1/sqrt(2*pi*sigma^2) * exp(-(x-mu).^2 / (2*sigma^2))

See also normcdf2 for the equivalent cumulative distribution.

Example

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

% Generate curve
y1 = normpdf2(x, mu, sigma);
y2 = normpdf2(x, mu-1, sigma+2);
y3 = normpdf2(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) 1/sqrt(2*pi*o^2) * exp(-(x-u).^2 / (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 u, o and x, which represent mu, sigma 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 (mu, sigma, x) in the order specified in f's definition.

No comments:

AdSense