三维矩阵

时间:2011-07-08 08:29:44

标签: matlab

我有一个4×4×4的矩阵,我认为它是圆形的(所以行的第4个元素用第1个关闭,相同的用于列和页面)。

我们知道在3D中每个点都有26个邻居,可以表示为(i,j,k-1)(i,j,k + 1)等但我不知道如何让matlab知道点(1,1,1)的a(i,j,k-1)邻居不是(1,1,0)但是(因为它是圆形的)(1,1,4)以及那个点( 2,4,3)的邻居(i,j + 1,k)不是(2,5,3)而是(2,1,3)。换句话说,我如何制作循环?

谢谢

2 个答案:

答案 0 :(得分:1)

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

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

你可能想要编写一个封装“循环”矩阵访问的函数,这样你就必须只在一个地方进行索引计算。

答案 1 :(得分: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
相关问题