how to repeat a code until a certain input has been recieved
조회 수: 8 (최근 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!
