MATLAB: How do 3D coordinates map to a 3D matrix

3d mapping to matrix

The project is about point cloud. Given a large number of 3-D coordinates (x-y-z) with all intensities are the same, say 1 or 255.
The range of x, y and z shown as follows.
* -113<x<158;
* -136<y<135 and
* -771<z<-500.
# If i create a 272 by 272 by 272 matrix, how can i map those 3-D coordinates to the matrix?
A = zeros(272, 272, 272);
# I know the matrix index starts from 1 in MAT-LAB. Should I create a 3-D grid to do mapping?

Best Answer

I assume in the following piece of code that your 3D points are listed in an N-by-3 vector named 'points'.
% Min and max values
xmin = -113;
xmax = 158;
ymin = -136;
ymax = 135;
zmin = -771;
zmax = -500;
% Initialize output matrix in which a non-zero entry indicates a 3D point exists in the input set
mat = zeros(xmax-xmin+1, ymax-ymin+1, zmax-zmin+1);
% For all 3D points
for p=1:size(points, 1)
if ( points(p,1)>xmax || points(p,1)<xmin || points(p,2)>ymax || points(p,2)<ymin || points(p,3)>zmax || points(p,3)<zmin )
fprintf('Error: point %d is out of bounds.\n', p);
else
i = points(p,1) - xmin + 1;
j = points(p,2) - ymin + 1;
k = points(p,3) - zmin + 1;
mat(i, j, k) = mat(i, j, k) + 1;
end
end
The output matrix 'mat' contains non-zero entries when a 3D point exists, but you'll have to convert into indices. For example, if the first point in 'points' is [29 -76 -614], then
mat(29-xmin, -76-ymin, -614-zmin) ~= 0
Related Question