%%%%%%均匀分布的概率密度函数估计
function myparzen01()
clc;
close all;
clear all;
N = 20480; %调整N可改变所求概率密度函数的精度
x = linspace(-3, 3, 100);
n=N;
i=1;
while i<=n %产生均匀分布双峰概密随机数,x分布在-2.5到-2之间的概率为0.5;x分布在0到2之间的概率为0.5
R(i)=rand(1);
if R(i)>0.5
p(1,i)=2*rand(1);
elseif R(i)<0.5
p(1,i)=0.5*rand(1)-2.5;
else
null;
end
i=i+1;
end
f=p;
X = zeros(N, 1);
X=f;
p = Parzen(x, X, 0.25, 1);
subplot(3,3,1);plot(x, p);title('N =1, h1 = 0.25');axis([-3, 3, 0, 1.5]);grid on;
p = Parzen(x, X, 1, 1);
subplot(3,3,2);plot(x, p);title('N =1, h1 = 1');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 4, 1);
subplot(3,3,3);plot(x, p);title('N =1, h1 = 4');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 0.25, 16);
subplot(3,3,4);plot(x, p);title('N =16, h1 = 0.25');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 1, 16);
subplot(3,3,5);plot(x, p);title('N =16, h1 = 1');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 4, 16);
subplot(3,3,6);plot(x, p);title('N =16, h1 = 4');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 0.25,N);
subplot(3,3,7);plot(x, p);title('N =256, h1 = 0.25');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 1, N);
subplot(3,3,8);plot(x, p);title('N =256, h1 = 1');axis([-3, 3, 0, 1.5]); grid on;
p = Parzen(x, X, 4,N);
subplot(3,3,9);plot(x, p);title('N =256, h1 = 4');axis([-3, 3, 0, 1.5]); grid on;
grid on;
end
function p = Parzen(x, X, h1, N) % x为横坐标; X为样本; h1用来调节窗宽h; N为样本个数.
h = h1 / sqrt(N); % h为窗宽.
sum = zeros(1, 100);
for i = 1:N
sum = sum + normpdf((x - X(i))/h, 0, 1); %用正态窗函数作Parzen窗估计
end
p = sum/(N * h);
end