Your original M
-dimensional container is A
.
We want to create a new N
-dimensional container B
that will hold all content of A
.
First we have to figure out a mapping where we can easily find the same element in A
and in B
.
Let's use some examples to deduce how the mapping could be:
(1) M = 2, N = 1
A: a * b B: c
we can set the dimension c to be a * b, thus we have
A[i][j] = B[i * c + j]
(2) M = 3, N = 1
A: a * b * c B: d
d = a * b * c
A[i][j][k] = B[(i * b * c) + (j * c) + k]
(3) M = 3, N = 2
A: a * b * c B: d * e
d = a, e = b * c
A[i][j][k] = B[i][j * c + k]
(4) M = 4, N = 1
A: a * b * c * d B: e
e = a * b * c * d
A[i][j][k][l] = B[(i * b * c * d) + (j * c * d) + (k * d) + l]
(5) M = 5, N = 4
A: a * b * c * d * e B: u * v * w * x
u = a, v = b, w = c, x = d * e
A[i][j][k][l][m] = B[i][j][k][(l * e) + m]
(6) M = 5, N = 2
A: a * b * c * d * e B: f * g
f = a, g = b * c * d * e
A[i][j][k][l][m] = B[i][(j * c * d * e) + (k * d * e) + (l * e) + m]
If A has M dimensions a1, a2, ..., aM and B has N dimensions b1, b2, ..., bN, we can say that:
if M > N, then for all 0 < i < N, bi = ai and bN = aN * aN+1 * ... * aM.
This way we know how to create B and the size of each dimension of it.
With the mapping function shown in the examples, you can easily convert any M
-dimension matrix to a N
-dimension matrix.
If M < N
, you can do the same thing but in opposite direction.