how to repeat a code until a certain input has been recieved

5 visualizaciones (últimos 30 días)
zach
zach el 8 de Mayo de 2025
Comentada: zach el 9 de Mayo de 2025
i have little to no experience in MATLAB and basically i want my code to repeat a pattern infinitly until it recieves a certain input. I am using MATLAB arduino and just wondering if anyone has any ideas

Respuesta aceptada

Sam Chak
Sam Chak el 8 de Mayo de 2025
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)
Total number of points lies inside the circle 1259
disp('Total number of points lies outside the circle'), disp(noc)
Total number of points lies outside the circle 344
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)
3.1416

Más respuestas (0)

Categorías

Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by