for loop skipping an iteration

8 visualizzazioni (ultimi 30 giorni)
Nushaer
Nushaer il 27 Ott 2022
Commentato: Nushaer il 27 Ott 2022
My code is for simulating Buffon's Needle throwing experiment.
So I wanted to simulate the throwing needles part. The following code was supposed to create 3 figures each with 10, 100 and 1000 needles respectively.
fig=0;
n=[10 100 1000];
for n=n
fig=fig+1;
figure(fig)
hold on
for s=1:n
needle
end
hold off
end
function needle
mid_x=0.5+9*rand(1,1);
mid_y=0.5+9*rand(1,1);
slope=tan(2*pi*rand(1,1));
x1=mid_x+1/sqrt((1+slope^2));
y1=slope*(x1-mid_x)+mid_y;
x2=mid_x-1/sqrt((1+slope^2));
y2=slope*(x2-mid_x)+mid_y;
plot([x1 x2],[y1 y2])
end
however, it's showing two figures; one titled figure 1 but with 100 lines and the other figure 3 with 1000 lines. Can anyone tell me where the problem is?
  2 Commenti
Bjorn Gustavsson
Bjorn Gustavsson il 27 Ott 2022
One general advice is to never ever again use the construct
n=[10 100 1000];
for n=n
end
Nothing good can come out of that in the long run. Use different names, if for no other reason to make it clear which is what where.
Nushaer
Nushaer il 27 Ott 2022
I'm just starting out. Thanks for the tip.

Accedi per commentare.

Risposta accettata

Karim
Karim il 27 Ott 2022
I would use a separate variable for the for-loop. See below with the adjusmtents.
n = [10 100 1000];
for i = 1:numel(n)
figure(i)
hold on
for s = 1:n(i)
needle
end
hold off
grid on
title("Figure with "+num2str(n(i))+" needles")
end
function needle
mid_x=0.5+9*rand(1,1);
mid_y=0.5+9*rand(1,1);
slope=tan(2*pi*rand(1,1));
x1=mid_x+1/sqrt((1+slope^2));
y1=slope*(x1-mid_x)+mid_y;
x2=mid_x-1/sqrt((1+slope^2));
y2=slope*(x2-mid_x)+mid_y;
plot([x1 x2],[y1 y2])
end

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by