找出“扁平化索引”来自“堆叠索引”数组的

发布于 2024-10-13 07:05:08 字数 660 浏览 0 评论 0原文

我试图提出一个方程,从“堆叠索引”中以数学方式确定数组的“扁平索引”。请观察以下 Ruby 示例。

matx = [[[ 1, 2, 3, 4],
         [ 5, 6, 7, 8]],

        [[ 9,10,11,12],
         [13,14,15,16]]]

在此示例中,matx 是一个三维矩阵,元素 7 位于 matx[0][1][2]。然而,在下一个示例中:

matx.flatten!  # => [1, 2, 3, 4, 5, 6, 7, 8, 
               #     9, 10, 11, 12, 13, 14, 15, 16]

现在元素 7 位于 matx[6]

所以本质上,我正在寻找一种方法,在给定矩阵的维度和特定元素的索引集的情况下,从堆叠矩阵转换为展平矩阵。 Reverse 也很棒,但我认为获得该结果的方法与获得此结果的方法类似(但本质上是相反的)。 我意识到 reverse 实际上并不是一个函数,因为没有一种必然能够区分 5 映射到 [2,3] 还是 [3,2] 等的方法。所以我不打算研究这个。

I'm trying to come up with an equation to mathematically determine the "flattened index" of an array from the "stacked index." Observe the following example in Ruby.

matx = [[[ 1, 2, 3, 4],
         [ 5, 6, 7, 8]],

        [[ 9,10,11,12],
         [13,14,15,16]]]

In this example, matx is a three dimensional matrix, and the element 7 is located at matx[0][1][2]. However, in the next example:

matx.flatten!  # => [1, 2, 3, 4, 5, 6, 7, 8, 
               #     9, 10, 11, 12, 13, 14, 15, 16]

Now the element 7 is located at matx[6].

So essentially, I'm looking for a way to, given the dimensions of the matrix and the set of indices for the particular element, convert from the stacked matrix to the flattened matrix. Reverse would be awesome, too, but I figure the way to get that is similar (but essentially reversed) to the method of obtaining this result. I realized that reverse is not actually a function, because there's no way to necessarily tell the difference as to whether 5 maps to [2,3] or [3,2], etc. So I'm not going to look into that one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末蓝 2024-10-20 07:05:08
class Index
  def initialize *dims
    @dims = dims.reverse
  end

  def if_flat *subs
    raise unless @dims && @dims.size == subs.size
    res = 0
    subs.reverse.each_with_index { |s, i| res += s * @dims[0...i].inject(1) { |m, e| m * e }}
    res
  end
end
puts Index.new(2, 2, 4).if_flat 0, 1, 2
class Index
  def initialize *dims
    @dims = dims.reverse
  end

  def if_flat *subs
    raise unless @dims && @dims.size == subs.size
    res = 0
    subs.reverse.each_with_index { |s, i| res += s * @dims[0...i].inject(1) { |m, e| m * e }}
    res
  end
end
puts Index.new(2, 2, 4).if_flat 0, 1, 2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文