how to repeat a code until a certain input has been recieved
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Sam Chak
am 8 Mai 2025
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)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu MATLAB Support Package for Arduino Hardware finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
