C2: uniform probability mass
C2: uniform probability mass
We start by deciding on the range, and writing and computing the analytical functions for the probability density and cumulative density functions:
range=[0 3]; truncation=[0 3]; rangeextended=[range(1) range(2)]+.065*diff(range)*[-1 1];
t=linspace(rangeextended(1),rangeextended(2),5001);
pdfnow=@(tnow,rangenow) ones(size(tnow))./diff(rangenow);
cdfnow=@(tnow,rangenow) (tnow-rangenow(1))/diff(rangenow);
pd=pdfnow(t,range); cpd=cdfnow(t,range);
pd(t<truncation(1))=0; pd(t>truncation(2))=0;
cpd(t<truncation(1))=0; cpd(t>truncation(2))=cpd(find(t<=truncation(2),1,'last'));
and continue to define the number of segments (N), the segment edges (segs) and centers (xstem), as well as the probability densities at each segment center (pstem):
N=4;
segs=linspace(range(1),range(2),N+1);
dx=diff(segs(1:2))/2;
xstem=dx+segs(1:N); pstem=interp1(t,pd,xstem);
masses=0; masses(end+[1:N])=(2*dx)*pstem;
where the masses variable encodes the approximate probability mass contained within each segment. The plots of the corresponding probability density (first subplot) and cumulative density (second subplot) are:
figure; subplot(2,1,1); hold on; %upper panel: pdf & approx masses
plot(t,pd,'k-','LineWidth',2.2) %analytically correct pdf
for n=1:N+1, plot(segs(n)*[1 1],[0 pd(findnearestN(t(:),segs(n),1))],'k:'); end
for n=1:N, plot(xstem(n)*[1 1],[0 masses(n+1)],'k-'); end
for n=1:N, plot(xstem(n)+dx*[-1 1],masses(n+1)*[1 1],'k-','LineWidth',5); end
axis([rangeextended 0 1.05*(max([max(pd) max(masses)]))])
subplot(2,1,2); hold on %lower panel: cdf & sums of approx masses
plot(range,[1 1],'k--') %reference line for unity total mass
plot(t,cpd,'k-','LineWidth',2.2) %analytically correct cdf
for n=1:N, plot(xstem(n)+dx*[-1 1],[sum(masses(1:n)) sum(masses(1:n+1))],'k-','LineWidth',5); end %approx masses
for n=1:N+1, plot(segs(n)*[1 1],[0 cpd(findnearestN(t(:),segs(n),1))],'k:'); end %segment boundaries
axis([rangeextended 0 1.05])
The plot for any number of segments (e.g., the 21-segment plots) can be obtained simply by changing the value of the N variable.