MATLAB: How to find the overlapping volume of multiple 3D rectangles

convhullninhullvolume

Hi! I am currently trying to calculate the overlapping region between 2 3D rectanges. I have created 2 3D rectangles (via convhulln of 8 different vertices each) and am attempting to identify and calculate the overlapping volume between these 2 rectangles (Lets say they're rectangles A and B and you could say their axes are parallel to each other; none of the rectangles are tilted with respect to each other). Imagine if the 2 rectangles below are in 3-dimensional space and that they are 3D
1) Right now, I am only able to identify if vertices from either A or B lie in the other polyhedron via the function inhull (3D version of inpolygon), which outputs a logical array, with no idea of carrying on to identify the volume of the intersected region.
2) Furthermore, I have to subtract the 'overlapping region' from lets say the green 3D rectangle, and compare this green 3D rectangle to other rectangles and carry out the same process of volume identification and volume/region 'subtraction'. What I wish to end up with is a green rectangle region that has no intersection with all the other triangles that I have compared it against, and calculate its remaining volume. I will then subtract the original volume of this green 3D rectangle (obtained from convhulln) with this 'remainder' volume, to obtain the total volume that all the overlapped regions have occupied in a sense. Would there be any efficient method to this? As I have thousands of 3D rectangles to compare against the 'template' 3D green rectangle. Thank you!!

Best Answer

Try this simple script
clc,clear
% generate some data
[x1,y1,z1] = meshgrid([0 10]);
[x2,y2,z2] = meshgrid([4 15]);
y1 = y1 - 3;
% check if there is intersection
c1 = max(x1(:)) < min(x2(:)) || max(x2(:)) < min(x1(:));
c2 = max(y1(:)) < min(y2(:)) || max(y2(:)) < min(y1(:));
c3 = max(z1(:)) < min(z2(:)) || max(z2(:)) < min(z1(:));
[X,Y,Z] = deal(nan);
if c1 || c2 || c3 % if out of the limits
disp('there is no intersection')
else
X(1) = max(min(x1(:)),min(x2(:)));
X(2) = min(max(x1(:)),max(x2(:)));
Y(1) = max(min(y1(:)),min(y2(:)));
Y(2) = min(max(y1(:)),max(y2(:)));
Z(1) = max(min(z1(:)),min(z2(:)));
Z(2) = min(max(z1(:)),max(z2(:)));
end
[X,Y,Z] = meshgrid(X(1):X(2),Y(1):Y(2),Z(1):Z(2));
plot3(x1(:),y1(:),z1(:),'.b')
hold on
plot3(x2(:),y2(:),z2(:),'.r')
plot3(X(:),Y(:),Z(:),'.g')
hold off
h = legend('cube1','cube2','intersection cube');
set(h,'orientation','horizontal','location','north')
axis equal vis3d
Related Question