www.gusucode.com > stats 源码程序 matlab案例代码 > stats/CreateaPiecewiseLinearDistributionObjectUsingSpecifiedPaExample.m

    %% Create a Piecewise Linear Distribution Object Using Specified Parameters  

%% 
% Load the sample data. Visualize the patient weight data using a histogram. 
load hospital
histogram(hospital.Weight)    

%%
% The histogram shows that the data has two modes, one for female patients
% and one for male patients.  

%% 
% Compute the empirical cumulative distribution function (ecdf) for the data. 
[f,x] = ecdf(hospital.Weight);  

%% 
% Construct a piecewise linear approximation to the ecdf and plot both functions. 
f = f(1:5:end); % keep a less dense grid of points
x = x(1:5:end);

figure;
ecdf(hospital.Weight)
hold on
plot(x,f,'ro','MarkerFace','r') % overlay grid
plot(x,f,'k') % show interpolation     

%% 
% Create a piecewise linear probability distribution object using the piecewise
% approximation of the ecdf. 
pd = makedist('PiecewiseLinear','x',x,'Fx',f)  

%% 
% Generate 100 random numbers from the distribution. 
rw = random(pd,100,1);  

%% 
% Plot the random numbers to visually compare their distribution to the
% original data. 
figure;
histogram(rw)    

%%
% The random numbers generated from the piecewise linear distribution have
% the same bimodal distribution as the original data.