Problem with plotting result

2 views (last 30 days)
Tarek Mahjoub
Tarek Mahjoub on 29 Jul 2021
Commented: Tarek Mahjoub on 29 Jul 2021
Hi guys, I am new using Matlab and I've been posting some questions in the recent time and I hope you be patient with me. I am having a trouble with the code
c = 2; % constant
n = 100; % Generate 100 random variables.
% Set up the arrays to store variates.
x = zeros(1,n); % random variates
xy = zeros(1,n);% corresponding y values
rej = zeros(1,n);% rejected variates
rejy = zeros(1,n); % corresponding y values
irv = 1;
irej = 1;
while irv <= n
y = rand(1); % random number from g(y)
u = rand(1); % random number for comparison
if u <= 2*y/c
x(irv) = y;
xy(irv) = u*c;
irv = irv+1;
else
rej(irej) = y;
rejy(irej) = u*c; % really comparing u*c<=2*y
irej = irej + 1;
end
end
plot(x,xy)
plot(rej,rejy)
plot(0:1,2*y)
I wanted the result to be as follows : the graph of 2*y which is a segment and under this segment the accepted values and above the rejected ones. What is missing here? Thank you in advance

Answers (1)

Dave B
Dave B on 29 Jul 2021
I'm not sure if this is what you're looking for? (I just looked at your plotting code, not at the math):
clf
scatter(x, xy, 'filled')
hold on
scatter(rej, rejy, 'filled')
plot([0 1], [0 2], 'k', 'LineWidth', 2)
Key bits:
  • use scatter for non-connected points, you could also do plot(..., 'o') for circular markers but scatter is better
  • use hold on to plot multiple things on top of eachother
  • Not sure what you doing with y, it was a random number, but I think this is what you were after based on the description and the picture (?)
  1 Comment
Tarek Mahjoub
Tarek Mahjoub on 29 Jul 2021
Thanks a lot for the help with the plotting. Actually I was applying the acceptance-rejection method on the density function 2*y so the graph of that function was supposed to be the segment you plotted

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!