how to repeat a loop until a condition is met than draw histogramm
1 view (last 30 days)
Show older comments
what i want is to generate 2 uniforms randoms numbers 'u1' and 'u2' and evaluate the magnetude of the 2 nummbers .if the magnetude "d<1" it is transformed and scalled by u1 to finally draw a histogramm of the outpout result.
the pgroramm is looks like this .
repeat
u1=2*rand()-1;
u2=2*rand()-1;
d=(u1.^2)+(u2.^2);
until 0<d<1
G=sqrt((-2*log(d))/d);
return G*u1
0 Comments
Accepted Answer
Yongjian Feng
on 31 Aug 2021
Edited: Yongjian Feng
on 31 Aug 2021
Just use a while loop?
Try:
done = false;
while ~done
u1=2*rand()-1;
u2=2*rand()-1;
d=(u1.^2)+(u2.^2);
done = d > 0 && d < 1;
end
d
G=sqrt((-2*log(d))/d);
G*u1
More Answers (1)
Image Analyst
on 31 Aug 2021
You're not going to be able to generate many points before you get a squared distance of less than 1 and need to quit. I ran it several times and it was always done in the first pass - just was able to get one point. Nonetheless, you need to index your distance so you have an array of distances that you can pass into the histogram() function. Here is how you'd do it:
loopCounter = 1;
maxIterations = 100000; % Failsafe
% Preallocate space
distanceSquared = zeros(1, maxIterations);
while loopCounter <= maxIterations
u1=2*rand()-1;
u2=2*rand()-1;
distanceSquared(loopCounter) = (u1.^2)+(u2.^2);
% See if we need to quit. Quit when distanceSquared is less than 1.
if distanceSquared(loopCounter) < 1
% Crop off unused.
distanceSquared = distanceSquared(1 : loopCounter);
break;
end
loopCounter = loopCounter + 1;
end
caption = sprintf('Was able to generate %d distances.\n', loopCounter);
fprintf('%s\n', caption);
% Compute G from distanceSquared:
G = sqrt((-2*log(distanceSquared)) ./ distanceSquared);
histogram(G);
grid on;
title(caption);
xlabel('G');
ylabel('Count');
0 Comments
See Also
Categories
Find more on Histograms 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!