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

1 回表示 (過去 30 日間)
ad lyn
ad lyn 2021 年 8 月 31 日
回答済み: Image Analyst 2021 年 8 月 31 日
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

採用された回答

Yongjian Feng
Yongjian Feng 2021 年 8 月 31 日
編集済み: Yongjian Feng 2021 年 8 月 31 日
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 件のコメント
ad lyn
ad lyn 2021 年 8 月 31 日
and what's about the histogram? i need to draw the histogram of (G*u1) so i can get a gaussian distribution

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2021 年 8 月 31 日
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');

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by