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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by