# Monte carlo: intersection volume of cylinders

4 views (last 30 days)
Eric on 3 May 2015
Edited: John D'Errico on 3 May 2015
I have to calculate the intersection volume of three cylinder(radius=3) each of which lie on x,y,z axis perpendicular to one another. I'm using a 5x5x5 cube
I can't use any of the more advanced matlab functions as we haven't been taught it yet.
I tried manipulating code for the area of a circle in a 2D square to fit my current problem.
Here's what I got:
N= 10000; % number of points generated
a = -5;
b = 5;
r=3;
hits=0;
x = a + (b-a).*rand(N,1);
y = a + (b-a).*rand(N,1);
z = a + (b-a).*rand(N,1);
%count the hits
for j = 1:N
hits=hits+i(j);
end
misses = N-hits;
disp('hits')
disp(hits)
disp('misses')
disp(misses)
plot(x(i),y(i), z(i),'.g');
hold;
plot(x(~i),y(~i),z(~i),'.r');
xlabel('x');
ylabel('y');
zlabel('z');
title('Intersection Volume');
ERROR: Operands to the and && operators must be convertible to logical scalar values

John D'Errico on 3 May 2015
Edited: John D'Errico on 3 May 2015
It looks like you packed all of your errors into one line of code. Everything else seems reasonable.
First of all, you use & as the operator here, not &&. Use && ONLY for scalar tests, essentially in an if statement. This is because the && operator is a short-circuited one. For example, in the logical statement:
(0 == 1) && (a == b)
MATLAB is smart enough to not bother to evaluate the second clause, because it sees that the first part is always false, therefore the statement MUST be false. This is why the && and operators were introduced.
Next, you may think that this tests if all of the radii are less than r, it does nothing of the sort, even if you used & instead of &&.
Just because you might think in some short-hand notation, this does not mean you should your computer to understand what you mean.
hits = ones(1,N)*i;
##### 2 CommentsShow 1 older commentHide 1 older comment
John D'Errico on 3 May 2015
Edited: John D'Errico on 3 May 2015
I accept that. I think IF you know when to use a tool like sum, and can do so properly, then it makes perfect sense to use it. I'm soooo lazy though. Did you know that MATLAB charges by how many characters you use? (Only kidding.)