MATLAB: Calculate pi using monte-Carlo simulation with logical vector

logical vectorMATLABmonte carlopi

I want to know how to model the script for calculating pi using Monte-Carlo simulation with using logical vectors
I already know the method using for/if, but does not know the method with logical vector
Please let me know how to do it
the below script is for the method using for/if
clear
clc
inside = 0;
nmax = 10000;
for n = 1:nmax
x = rand;
y = rand;
x1=x-0.5;
y1=y-0.5;
if sqrt(x1^2+y1^2) <= 0.5
plot(x1,y1,'b.');
inside = inside + 1;
else
plot(x1,y1,'r.');
end
if ( mod(n,1000) == 0 )
pi = 4 * inside / n;
fprintf('%8.4f\n',pi);
end
hold on;
end
hold off;
pi = 4 * inside / nmax;
fprintf('%8.4f\n',pi);

Best Answer

nmax = 10000;
x = rand(nmax,1);
y = rand(nmax,1);
x1=x-0.5;
y1=y-0.5;
r = sqrt(x1.^2+y1.^2) ;
% get logicals
inside = r<=0.5 ;
outside = r>0.5 ;
% plot
plot(x1(inside),y1(inside),'b.');
hold on
plot(x1(outside),y1(outside),'r.');
% get pi value
thepi = 4*sum(inside)/nmax ;
fprintf('%8.4f\n',thepi)