MATLAB: Trying to run a while loop that increases a number of “experiments” in a for loop

for loophelpMATLABscriptwhile loop

i currently have two different scripts one with the while loop that says this:
close all; clear all; clc; format compact;
experiments = 1;
x = 0;
while x~=3.14159
PRoject;
experiments = experiments^10;
end
and a for loop script that says this:
%counter for how many of the needles crossed a line
crosses=0;
%number to trials being performed
x=0;
%loop that continues for desired amount of trials
for t=1:experiments
%center of a needle
mx=20*rand(1,experiments);
my=20*rand(1,experiments);
%random angle
a=rand(1,experiments)*pi*2;
%start of needle
sx=(mx+cos(a))/2;
sy=(my+sin(a))/2;
%end of needle
ex=(mx-cos(a))/2;
ey=(my-sin(a))/2;
%see if needle crosses line
crossed=(ceil(min(sx,ex))==floor(max(sx,ex)));
crosses=crossed+crosses;
prob=crosses/experiments;
p=mean(prob);
end
x=2/p
The output is this repeated until stopped:
x =
Inf
x =
2
x =
Inf

Best Answer

Have you tried using breakpoints? Then you know why it is such a bad idea to use clear all instead of just clear or clearvars. And why isn't your second script a function? That would help a lot with debugging.
(Also, since you don't open any figures, why would you bother closing everything?)
But there are more fundamental problems here:
  • Pie~=3.14159 will never return false, as there is a very large change that the binary represenation of your estimation is not exactly equal to 3.14159
  • The loop in your second script doest actually depend on the value of t, so the only effect is on the value of crosses. If this is intentional you can move the calculation of prob and p outside the loop.
  • The number of expirements is not actually increasing, since 1^10 is still 1. If it were increasing, raising to the 10th power will quickly blow it up to inf, or to something large enough that mx=20*rand(1,experiments); will no longer fit in your memory.
I would suggest a complete re-structuring of your code into functions. And replace that first line with clearvars,clc.
Related Question