for loop skipping an iteration

4 Ansichten (letzte 30 Tage)
Nushaer
Nushaer am 27 Okt. 2022
Kommentiert: Nushaer am 27 Okt. 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 Kommentare
Bjorn Gustavsson
Bjorn Gustavsson am 27 Okt. 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 am 27 Okt. 2022
I'm just starting out. Thanks for the tip.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Karim
Karim am 27 Okt. 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by