for loop skipping an iteration

4 次查看(过去 30 天)
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 个评论
Bjorn Gustavsson
Bjorn Gustavsson 2022-10-27
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 2022-10-27
I'm just starting out. Thanks for the tip.

请先登录,再进行评论。

采纳的回答

Karim
Karim 2022-10-27
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by