Monte carlo: intersection volume of cylinders

6 次查看(过去 30 天)
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);
radiixy = sqrt(z.^2+y.^2);
radiixz = sqrt(x.^2+z.^2);
radiizy = sqrt(x.^2+y.^2);
i = radiixy && radiixz && radiizy <= r;
%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
John D'Errico 2015-5-3
编辑:John D'Errico 2015-5-3
It looks like you packed all of your errors into one line of code. Everything else seems reasonable.
i = radiixy && radiixz && radiizy <= r;
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 &&.
Do this instead:
i = (radiixy <= r) & (radiixz <= r) & (radiizy <= r);
Just because you might think in some short-hand notation, this does not mean you should your computer to understand what you mean.
Next, why have a loop to count the hits? Is sum really that advanced? How about this:
hits = ones(1,N)*i;
  2 个评论
Eric
Eric 2015-5-3
Thanks John.
You're right sum isn't advanced at all but the question specifically asks to not use matlab's inbuilt functions except for rand. Guess my tutor just wants to make sure we got the basics mastered.
Appreciate the help!
John D'Errico
John D'Errico 2015-5-3
编辑:John D'Errico 2015-5-3
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.)

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by