How do you build an array to plot it?

조회 수: 4 (최근 30일)
Kirsten Rawls
Kirsten Rawls 2016년 2월 6일
댓글: Star Strider 2016년 2월 7일
I'm writing code using monte carlo integration to approximate pi. I need to made a plot of the convergence to pi as I increase the number of iterations. I'm trying to build an array but I can't figure out how to initialize and plot it all without Matlab saying "Subscript indices must either be real positive integers or logicals." I don't know what initializations I should be using for the array, I've never used an array in Matlab before.
Here is what I have so far
i = 0;
p = 0;
k = 1;
g = 1;
n = max(size(k));
p(i) = (1:k);
Ndom(i) =(1:k);
Nint = 0;
Ndom = 0;
Adom = d*d';
tic
while k < 1000000
x = (d*rand)-r; %Run random number sequence for x
y = (d*rand)-r; %Run random number sequence for y
if (x.^2)+(y.^2)<= r.^2
Nint = Nint + 1; %Increase number of points within circle
else
end
if g*10.^g == k
i = i + 1;
Ndom(i) = k;
Aint = (Adom*Nint)./Ndom(i);
p(i) = Aint./(r.^2);
%for every 10th iteration calc p, plot it using semilogx or log(x) vs. y
%use array
semilogx(Ndom(i), p(i));
xlabel('Number of points');
ylabel('Pi calculation');
title('Calculation of pi using Monte Carlo integration');
n = n+1;
else
end
k = k+1;
end
Ndom = k;
Aint = (Adom*Nint)./Ndom;
p = Aint./ (r.^2);
toc
end
I built the code before trying to figure out how to plot it, just to make sure that the math was correct within an accepted error tolerance, and it works fine. I just can't figure out how to plot it.
  댓글 수: 2
Kirsten Rawls
Kirsten Rawls 2016년 2월 6일
I should note, I caught a couple mistakes in my code not related to the question, replaced n = n + 1 with g = g + 1.
Walter Roberson
Walter Roberson 2016년 2월 6일
I recommend
semilogx(Ndom(1:i), p(1:i));
as your current code only plots one point per graph.
Are you sure you only want to plot at iterations 10, 200, 3000, 40000, 500000 ?? Because that's what the test if g*10.^g == k is going to select for.

댓글을 달려면 로그인하십시오.

답변 (1개)

Star Strider
Star Strider 2016년 2월 6일
I didn’t run it, but after editing it (to include all your code as [{} code]) and looking at it, observed that the hold function could be your friend here.
  댓글 수: 4
Walter Roberson
Walter Roberson 2016년 2월 6일
To get them to join,
semilogx(Ndom(1:i), p(1:i));
with which "hold on" would probably not be needed.
Oh yes, put in
drawnow()
after the title() call.
Star Strider
Star Strider 2016년 2월 7일
Thank you, Walter!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by