Monte carlo: intersection volume of cylinders
2 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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.
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 Comments
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.)
More Answers (0)
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!