for loop skipping an iteration
조회 수: 1 (최근 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
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.
채택된 답변
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 Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!