给定一对两个变量(X,Y),如何在vanilla MATLAB (没有工具箱)中生成和绘制经验联合PDF和CDF?
发布于 2013-09-05 23:58:01
原始答案(Matlab R2015a或更低版本)
数据包括:
随机变量X,Y:定义为在x,y轴处的样本向量X,
X:由向量x_axis,y_axis定义。边缘必须明显地增加,但不需要均匀间隔。生成的PDF和CDF定义在由x和y边确定的矩形的中心。
要以三维形式打印结果,请使用surf(...)而不是imagesc(...)。
clear all
%// Data (example):
X = randn(1,1e5); %// random variables.
Y = randn(1,1e5);
x_axis = -3:.2:3; %// Define edges of bins for x axis. Column vector
y_axis = -3:.2:3; %// Same for y axis
%// Compute corners of 2D-bins:
[x_mesh_upper,y_mesh_upper] = meshgrid(x_axis(2:end),y_axis(2:end));
[x_mesh_lower,y_mesh_lower] = meshgrid(x_axis(1:end-1),y_axis(1:end-1));
%// Compute centers of 1D-bins:
x_centers = (x_axis(2:end)+x_axis(1:end-1))/2;
y_centers = (y_axis(2:end)+y_axis(1:end-1))/2;
%// Compute pdf:
pdf = mean( bsxfun(@le, X(:), x_mesh_upper(:).') ...
& bsxfun(@gt, X(:), x_mesh_lower(:).') ...
& bsxfun(@le, Y(:), y_mesh_upper(:).') ...
& bsxfun(@gt, Y(:), y_mesh_lower(:).') );
pdf = reshape(pdf,length(x_axis)-1,length(y_axis)-1); %// pdf values at the
%// grid points defined by x_centers, y_centers
pdf = pdf ./ (y_mesh_upper-y_mesh_lower) ./ (x_mesh_upper-x_mesh_lower);
%// normalize pdf to unit integral
%// Compute cdf:
cdf = mean( bsxfun(@le, X(:), x_mesh_upper(:).') ...
& bsxfun(@le, Y(:), y_mesh_upper(:).') );
cdf = reshape(cdf,length(x_axis)-1,length(y_axis)-1);
%// Plot pdf
figure
imagesc(x_centers,y_centers,pdf)
axis xy
axis equal
colorbar
title 'pdf'
%// Plot cdf
figure
imagesc(x_centers,y_centers,cdf)
axis xy
axis equal
colorbar
title 'cdf'


编辑答案(Matlab R2015b或更高版本)
Matlab R2015b包含一个执行所有工作的histogram2函数。它会自动进行规范化,以获得PDF (给定适当的输入标志),甚至是CDF。
使用与上面相同的示例,
clear all
%// Data (example):
X = randn(1,1e5); % random variables.
Y = randn(1,1e5);
x_axis = -3:.2:3; % Define edges of bins for x axis. Column vector
y_axis = -3:.2:3; % Same for y axis
%// Compute and plot pdf
figure
histogram2(X, Y, x_axis, y_axis, 'Normalization', 'pdf')
%// Compute and plot cdf
figure
histogram2(X, Y, x_axis, y_axis, 'Normalization', 'cdf')


https://stackoverflow.com/questions/18639518
复制相似问题