将 3D 中的元素映射 "triangle" 到线性结构
Mapping elements in 3D lower "triangle" to linear structure
这是现有 question 的 3D 版本。
形状为 (n,n,n)
的 3D 数组 M[x,y,z]
应映射到仅包含 x<=y<=z 元素的平面向量,以便保存 space。所以我需要的是类似于二维情况的表达式(index := x + (y+1)*y/2
)。我试图推导一些公式,但就是做不对。请注意,向量中的元素顺序无关紧要。
等式的 3D 版本是
index := (z * (z+1) * (z+2)) / 6 + (y * (y+1))/2 + x
这是 user3386109 的答案的扩展,用于将形状为 (n,...,n)
的任意维度 d
的数组映射到大小为 size(d,n)
的向量,该向量仅包含其索引满足 X_1 <= X_2 <= ... <= X_d
.
如果有人感兴趣,这里是@letmaik 在python 中回答的代码:
import math
from itertools import combinations_with_replacement
import numpy as np
ndim = 3 # The one you'd like
size = 4 # The size you'd like
array = np.ones([size for _ in range(ndim)]) * -1
indexes = combinations_with_replacement([n for n in range(size)], ndim)
def index(*args):
acc = []
for idx, val in enumerate(args):
rx = np.prod([val + i for i in range(idx + 1)])
acc.append(rx / math.factorial(idx + 1))
return sum(acc)
for args in indexes:
array[args] = index(*args)
print(array)
虽然我必须承认它可以改进,因为元素的顺序看起来不自然。
这是现有 question 的 3D 版本。
形状为 (n,n,n)
的 3D 数组 M[x,y,z]
应映射到仅包含 x<=y<=z 元素的平面向量,以便保存 space。所以我需要的是类似于二维情况的表达式(index := x + (y+1)*y/2
)。我试图推导一些公式,但就是做不对。请注意,向量中的元素顺序无关紧要。
等式的 3D 版本是
index := (z * (z+1) * (z+2)) / 6 + (y * (y+1))/2 + x
这是 user3386109 的答案的扩展,用于将形状为 (n,...,n)
的任意维度 d
的数组映射到大小为 size(d,n)
的向量,该向量仅包含其索引满足 X_1 <= X_2 <= ... <= X_d
.
如果有人感兴趣,这里是@letmaik 在python 中回答的代码:
import math
from itertools import combinations_with_replacement
import numpy as np
ndim = 3 # The one you'd like
size = 4 # The size you'd like
array = np.ones([size for _ in range(ndim)]) * -1
indexes = combinations_with_replacement([n for n in range(size)], ndim)
def index(*args):
acc = []
for idx, val in enumerate(args):
rx = np.prod([val + i for i in range(idx + 1)])
acc.append(rx / math.factorial(idx + 1))
return sum(acc)
for args in indexes:
array[args] = index(*args)
print(array)
虽然我必须承认它可以改进,因为元素的顺序看起来不自然。