-1

由二维组成的矩阵如下:

for (i = 0; i <length*length; i++)
    Mat [i/length, i% length] = i;

那么如何循环遍历 3d 矩阵?

for (i = 0; i <length*length*length; i++)
    Mat [?] = i;
4

2 回答 2

1

只需将index写入base length,您将获得 N 个维度的通用解决方案。

因此,对于 3D,它将是

for (i = 0; i <length*length*length; i++)
     p = i;
     z = p % length;

     p /= length;
     y = p % length;

     p /= length;
     x = p;
     Mat [x, y, z] = i;

或者只是更短

for (i = 0; i <length*length*length; i++)
     Mat[i / (length*length), (i/length) % length, i % length] = i
于 2013-10-20T16:07:42.980 回答
1
for (i = 0; i <length*length*length; i++)
    q = i/(length*length);
    r = i%(length*length);
    Mat [q, r/length, r%length] = i;

Python

k = 3

for i in xrange(k * k * k):
    q = i / (k * k)
    r = i % (k * k)
    print q, r / k, r % k

输出

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2
于 2013-10-20T15:27:21.500 回答