2015-05-11 52 views
3

我試圖創建一個1和0的三維矩陣。我想通過在它們之間形成一行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]; 

我能夠使用這個代碼

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做到在2D?

+2

3D Bresenham? http://www.mathworks.com/matlabcentral/fileexchange/21057-3d-bresenham-s-line-generation – knedlsepp

+0

是的,看起來我的答案是Bresenham的實現。毫不奇怪,我記住了舊的辛克萊譜PLOT;)。 –

回答

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 

請原諒醜陋的代碼,我做到了這一點急於;)。

+0

不,這是完美的!謝謝一堆 –