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

1 次查看(过去 30 天)
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 个)

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