how to repeat a loop until a condition is met than draw histogramm

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Yongjian Feng
Yongjian Feng il 31 Ago 2021
Modificato: Yongjian Feng il 31 Ago 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
  1 Commento
ad lyn
ad lyn il 31 Ago 2021
and what's about the histogram? i need to draw the histogram of (G*u1) so i can get a gaussian distribution

Accedi per commentare.

Più risposte (1)

Image Analyst
Image Analyst il 31 Ago 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');

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by