MATLAB: How to determine whether point lies within pyramid volume

3dmonte carlopyramidrandom numbervectorvolume

A square pyramid is described by five points E0, E1, E2, E3, E4. eg E0= [0,0,1];E1= [1,1,0]; E2= [-1,1,0]; E3= [-1,-1,0]; E4= [1,-1,0], how to determine if giving point p[x,y,z] is located within the pramid volume or not. i need the algorithms or the mathematical equation.

Best Answer

Because the pyramid is regular, the algorithm is easy:
E0 = [ 0, 0, 1];
E1 = [ 1, 1, 0];
E2 = [-1, 1, 0];
E3 = [-1, -1, 0];
E4 = [ 1, -1, 0];
% Define the parameters of the pyramid:
Pyramid.Z = E0(3);
Pyramid.Base = [min(E(:, 1)), max(E(:, 1)), min(E(:, 2)), max(E(:,2))]
% Choose random points in the cuboid surrounding the pyramid:
P = rand(10000, 3) .* [2, 2, 1] - [1, 1, 0];
% Select points inside the pyramid:
T = inPyramid(P, Pyramid);
P = P(T, :);
% Show the result:
figure;
plot3(P(:,1), P(:,2), P(:,3), '.')
hold on
plot3(E0(1), E0(2), E0(3), 'ro');
plot3(E1(1), E1(2), E1(3), 'ro');
plot3(E2(1), E2(2), E2(3), 'ro');
plot3(E3(1), E3(2), E3(3), 'ro');
plot3(E4(1), E4(2), E4(3), 'ro');
xlabel('x')
ylabel('y')
zlabel('z')
For a point with at Z==0, you have to check, if it is inside the square. This square is shrinking linearily with the height until Z==1.
function T = inPyramid(P, Pyramid)
% P: 3D position as [N x 3] matrix
% Pyramid: Struct, .Z: Height of pyramid
% .Base: minimum and maximum of X and Y positions at the
% base as [1 x 4] vector
S = Pyramid.Base .* (Pyramid.Z - P(:, 3)) / Pyramid.Z;
T = (P(:, 3) >= 0 & P(:, 3) <= Pyramid.Z) & ... % Inside Z range
(P(:, 1) >= S(:, 1) & P(:, 1) <= S(:, 2)) & ... % Inside X range
(P(:, 2) >= S(:, 3) & P(:, 2) <= S(:, 4)); % Inside Y range
end
This is elementary maths only.
A constructive approach instead of this rejection method: