MATLAB: PDF function does not give same result as normpdf

normpdf

Hello all, I'm using the following function to create the PD of a RV
function [ X, f ] = Normdist( mu, sigma, min_x, max_x, n )
X = zeros(n,1);
x = min_x;
dx = (max_x - min_x)/n;
for k = 1:n
X(k) = x;
f(k) = 1/sqrt(2*pi*sigma)*exp(-(x-mu)^2/(2*sigma));
x = x+dx;
end
end
I call it as follows:
[LRV, LPDF] = Normdist(0, 2.5, -10, 10, 7);
LRV = [-10; -7,142; -4,285; -1,428; 1,428; 4,285; 7,14]
but when I call:
A = normpdf(linspace(-10,10,7),0,2.5)
I get:
A = [5,353; 0,004; 0,065; 0,159; 0,065; 0,004; 5,353]
what is wrong with the function? George.

Best Answer

You need to calculate ‘x’ differently (so that it creates the same interval that linspace does), and square ‘sigma’ in the denominator of the exp argument:
X = zeros(n,1);
f = zeros(n,1);
x = min_x;
dx = (max_x - min_x)/(n - 1);
for k = 1:n
X(k) = x;
f(k) = 1/(sqrt(2*pi)*sigma)*exp(-(x-mu)^2/(2*sigma^2));
x = x+dx;
end