【问题标题】:Mapping elements in 3D lower "triangle" to linear structure将 3D 下“三角形”中的元素映射到线性结构
【发布时间】:2015-03-12 22:58:34
【问题描述】:

这是现有 question 的 3D 版本。

形状为 (n,n,n) 的 3D 数组 M[x,y,z] 应映射到仅包含 xindex := x + (y+1)*y/2)。我试图推导出一些公式,但无法正确。请注意,向量内的元素顺序无关紧要。

【问题讨论】:

    标签: arrays algorithm matrix indexing


    【解决方案1】:

    这是 user3386109 的答案的扩展,用于将形状为 (n,...,n) 的任意维度数组 d 映射到大小为 size(d,n) 的向量中,该向量仅包含索引满足 X_1 <= X_2 <= ... <= X_d 的元素。

    【讨论】:

      【解决方案2】:

      方程的 3D 版本是

      index := (z * (z+1) * (z+2)) / 6 + (y * (y+1))/2 + x
      

      【讨论】:

      • 太好了,谢谢!您能简要解释一下您是如何得出 6 的吗?看起来它很容易扩展到任意维度。
      • @neo 看来您可以将其扩展到其他维度。但是,我无法证明它适用于 4D。 3D 的公式可以从平方和推导出来,维基百科称之为 Square pyramidal numbers,这就是 6 的来源。
      • 完成3D案例,能否给出输入数组为(n,n,n)时得到的向量的长度?
      • @neo 我相信这将是坐标(n,0,0) 的索引,即数组中not的第一个坐标的索引。因此size := (n * (n+1) * (n+2)) / 6
      • 谢谢!我刚刚弄清楚了 4D 案例:index := (l * (l+1) * (l+2) * (l+3) )/24 + (k * (k+1) * (k+2))/6 + (j * (j+1))/2 + i 对应于M[i,j,k,l],并且向量的大小为n*(n+1)*(n+2)/6*(n+3)/4。 24=6*4。
      【解决方案3】:

      如果有人感兴趣,这里是@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)
      

      虽然我必须承认它可以改进,因为元素的顺序看起来不自然。

      【讨论】:

        猜你喜欢
        • 2011-06-15
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 2014-07-08
        • 2012-11-18
        • 1970-01-01
        相关资源
        最近更新 更多