for loop skipping an iteration

6 views (last 30 days)
Nushaer
Nushaer on 27 Oct 2022
Commented: Nushaer on 27 Oct 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 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 27 Oct 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 on 27 Oct 2022
I'm just starting out. Thanks for the tip.

Sign in to comment.

Accepted Answer

Karim
Karim on 27 Oct 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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!