在多维矩阵中连接两个点

时间:2015-05-11 17:13:22

标签: matlab matrix multidimensional-array distance shortest

我正在尝试创建一个1&0和3的3d矩阵。我想通过在它们之间形成1行来连接2个点(最短距离)。

它看起来像这样,但在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];

我可以使用此代码在2d内完成此操作

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)

如何将此方法扩展为3d?

1 个答案:

答案 0 :(得分:1)

完全取决于你所说的“连接”。但是,如果目标是起点和终点之间的单格宽区域,则看起来很像“一像素宽”线,可以定义如下。

% 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

请原谅丑陋的代码,我急忙这样做;)。