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

3 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Sam Chak
Sam Chak il 8 Mag 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

Più risposte (0)

Categorie

Scopri di più su MATLAB Support Package for Arduino Hardware in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by