how to repeat a code until a certain input has been recieved
3 次查看(过去 30 天)
显示 更早的评论
采纳的回答
Sam Chak
2025-5-8
Hi @zach
Here is a simple example estimate the value of π using the while loop to infinitely repeat the execution of instructions when condition is true.
%% Simple script to estimate the value of pi using Monte Carlo method
nic = 0; % initiate the number of points lies inside the circle
noc = 0; % initiate the number of points lies outside the circle
hold on
while true % repeat infinitely until condition is met
% generate random coordinates between -1 and 1
x = sign(2*rand - 1)*rand;
y = sign(2*rand - 1)*rand;
plot(x, y, '.', 'color', '#265EF5');
% compute the distance of (x, y) with relative to (0, 0)
d = sqrt(x^2 + y^2);
if d <= 1 % it lies inside the circle
nic = nic + 1; % count nic + 1
else
noc = noc + 1; % count noc + 1
end
% compute the estimation of the pi number
piEst = 4*(nic/(nic + noc));
% terminate the iteration if the condition is met
if abs(piEst - 3.1416) <= 1e-5
break
end
end
disp('Total number of points lies inside the circle'), disp(nic)
disp('Total number of points lies outside the circle'), disp(noc)
Total_iteration = nic + noc;
center = [0, 0];
radius = 1;
viscircles(center, radius);
hold off
xlabel('x'), ylabel('y')
title(sprintf('Total number of points is %d', Total_iteration))
axis equal
disp(piEst)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 MATLAB Support Package for Arduino Hardware 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
