Connecting two points in a multidimensional matrix

I am trying to create a 3d matrix from 1 and 0. I want to connect 2 points (shortest distance) by forming a line between them.

It will look something like this, but in 3d

path_pixels = [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0;

               0,0,0,1,0,0,0,0,0,0,0,0,0,0,0;

               0,0,0,0,1,0,0,0,0,0,0,0,0,0,0];

      

I can do it in 2d using this code

clc;
clear;
%matrix size

A = zeros(70);
A(20,20) = 1;   %arbitrary point

B = zeros(70);
B(40,40) = 1; %arbitrary point

D1 = bwdist(A);
D2 = bwdist(B);

D_sum = D1 + D2 ;

path_pixels = imregionalmin(D_sum);

spy(path_pixels)

      

How can I extend this method to 3d?

+3


source to share


1 answer


It depends on what you mean by "connect", exactly. But if the target is an area with one cell between the start and end points, then this is very similar to the "one-pixel width", which can be defined as follows.

% start and end point of line
a = [1 10 2];
b = [4 1 9];

% get diffs
ab = b - a;

% find number of steps required to be "one pixel wide" in the shorter
% two dimensions
n = max(abs(ab)) + 1;

% compute line
s = repmat(linspace(0, 1, n)', 1, 3);
for d = 1:3
    s(:, d) = s(:, d) * ab(d) + a(d);
end

% round to nearest pixel
s = round(s);

% if desired, apply to a matrix
N = 10;
X = zeros(N, N, N);
X(sub2ind(size(X), s(:, 1), s(:, 2), s(:, 3))) = 1;

% or, plot
clf
plot3(s(:, 1), s(:, 2), s(:, 3), 'r.-')
axis(N * [0 1 0 1 0 1])
grid on

      



Please excuse the ugly code, I did it in a hurry;).

+1


source







All Articles