Clear Filters
Clear Filters

How to simulate generated CDF in Matlab

3 views (last 30 days)
Sudhir Kumar
Sudhir Kumar on 25 Feb 2022
Edited: Torsten on 25 Feb 2022
How to generate samples from a given density function in matlab. The PDF of the random variable is given by
First I have evaluated its CDF which is given as
Note from Here I want to generate the random samples using the command "rand" in matlab. So I have tried through inverse method by equating this F_Z(z) to Uniform distribution. However my question is when I want to equate with uniform distribution which equation should I equate and is the first equation for z < 0 I will equate or the second equation should I equate to U. So that I can evaluate the inverse function and getting z in terms of U. Please suggest me.
So I inverted my distribution function and also equate with rand command which is formed as uniform distribution. When rand produces a value less than 0.5 I have taken the value of the inverse distribution function where z less than zero. and when rand produces I have taken the inverse distribution of the when z is greater than 0. I have attached my code and results too. computational CDF is coming correct but simulation results are not correct. Please suggest me where I am wrongl
When I am trying to generate samples from .
clc;
clear all;
close all;
%% Initialization of the pdf calculation for F_Z
a = 5;
z = linspace(-a/2,a/2,100000);
for i = 1:100000
if i<50000
F_z(i) = (1/2*(a^3))*(a+2*z(i))^3;
F_z(i) = (0.5/a^3)*(a+2*z(i))^3;
else
% F_z(i) = 0.5 - (1/2*(a^3))*((a-2*z(i))^3- a^3);
F_z(i) = -(0.5/a^3)*((a-2*z(i))^3-a^3) + 0.5;
end
end
plot(z,F_z);
hold on;
% Simulation by second method
N = 10^5;
for i = 1:N
x(i) = rand(1);
if x(i) <= 0.5
z_1(i) = (a/2)*((2*x(i))^(1/3)-1);
X_1(i) = x(i);
else
z_2(i)= (a/2)*(1 - (2 -2*x(i))^(1/3));
X_2(i) = x(i);
end
end
z_ran = [z_1 z_2];
X_f = [X_1 X_2];
plot(z_ran, X_f);
v = -a/2:0.001:a/2;
for k = 1:length(v)
c_0 = 0;
for p = 1:N
if z_ran(p)<=v(k)
c_0 = c_0 + 1;
end
end
cdf_v(k) = c_0/N;
end
plot(v,cdf_v)

Answers (1)

Torsten
Torsten on 25 Feb 2022
Edited: Torsten on 25 Feb 2022
a = 1;
N = 1e5;
x = rand(N,1);
y = [a/2*(-1+(2*x(x<=0.5)).^(1/3)) ; a/2*(1-(2*(1-x(x>0.5))).^(1/3))]
cdfplot(y)
hold on
T1 = linspace(-a/2,0,100);
T2 = linspace(0,a/2,100);
F1 = 1/(2*a^3)*(a+2*T1).^3;
F2 = 1-1/(2*a^3)*(a-2*T2).^3;
T = [T1,T2];
F = [F1,F2];
plot(T,F)

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!