2011-07-08 143 views
1

我有一个3D 4×4×4的矩阵,我认为它是圆形的(所以行的第4个元素与第1个元素关闭,列和页面也一样)。我们知道在3D中每个点有26个可以表示为(i,j,k-1)(i,j,k + 1)等的邻居,但是我不确定如何让matlab知道(1,1,1)的一个(i,j,k-1)邻居不是(1,1,0),但是(它是圆形的)(1,1,4)以及该点(2,4,3)的邻居(i,j + 1,k)不是(2,5,3),而是(2,1,3)。换句话说,我该如何使它通告?3维矩阵

谢谢

回答

1

MATLAB没有这种内置的工具,但访问您的矩阵时达到你想要的效果,你可以使用mod(模数)函数。为了说明这一点上的向量:

v=[1 2 3]; 
i=5; 
result=v(mod(i-1, length(v))+1); 
% assigns 2 to 'result' 

你可能会想这么写,你必须做的指数计算只在一个地方,它封装了“圆形”矩阵接入功能。

+0

好了,所以你基本上是说,我有在我的情况下用4调制它,然后它会自动将0作为4和5作为1. – kojikurac

+0

是的,没错。由于MATLAB的索引是基于一个的,所以除了模数之外,还需要'-1'和'+1'(如我的代码所示)。 –

+0

谢谢,Hvala,Grazie,Danke,Merci! – kojikurac

1

这个想法是使用MOD函数作为@MartinB的解释。这里是一些代码来有效地计算每个点的邻居在你的立方体型4x4x4:

%# generate X/Y/Z coordinates of each point of the 4x4x4 cube 
sz = [4 4 4];       %# size of the cube along each dimension 
[X Y Z] = ndgrid(1:sz(1),1:sz(2),1:sz(3)); 
coords = [X(:) Y(:) Z(:)]; 

%# generate increments to get the 26 neighbors around a 3D point 
[X Y Z] = ndgrid([-1 0 1], [-1 0 1], [-1 0 1]); 
nb = [X(:) Y(:) Z(:)]; 
nb(ismember(nb,[0 0 0],'rows'),:) = []; %# remove the row [0 0 0] 

%# for each 3D point, compute its neighbors 
allNeighbors = zeros([size(nb,1) 3 size(coords,1)]); 
szMod = repmat(sz, [size(nb,1) 1]); 
for i=1:size(coords,1) 
    cc = bsxfun(@plus, nb, coords(i,:)); %# find 26 neighbors of coords(i,:) 
    cc = mod(cc-1,szMod)+1;    %# wrap around circularly 

    allNeighbors(:,:,i) = cc;   %# save them for later processing 
end 

产生的邻居的顺序如下:

>> nb 
nb = 
    -1 -1 -1  %# read as: (i-1,j-1,k-1) 
    0 -1 -1  %# read as: (i,j-1,k-1) 
    1 -1 -1  %# ... 
    -1  0 -1 
    0  0 -1 
    1  0 -1 
    -1  1 -1 
    0  1 -1 
    1  1 -1 
    -1 -1  0 
    0 -1  0 
    1 -1  0 
    -1  0  0 
    1  0  0 
    -1  1  0 
    0  1  0 
    1  1  0 
    -1 -1  1 
    0 -1  1 
    1 -1  1 
    -1  0  1 
    0  0  1 
    1  0  1 
    -1  1  1 
    0  1  1 
    1  1  1