【问题标题】:Symmetrically adressable matrix对称可寻址矩阵
【发布时间】:2009-09-15 04:48:36
【问题描述】:

我希望在 python 中创建一个具有对称寻址的整数二维矩阵(即 matrix[2,3] 和 matrix[3,2] 将返回相同的值)。整数将对它们进行加减运算,并用于逻辑比较。我最初的想法是预先创建整数对象,并尝试用一些 Python 等价的指针填充列表列表。不过,我不知道该怎么做。实现这一点的最佳方法是什么,我应该使用列表还是其他数据结构?

【问题讨论】:

  • 但从数学上讲,这应该行不通 - 至少,如果我对 Calc 1 的回忆是正确的
  • 我不确定我是否理解。什么不起作用?

标签: python data-structures matrix


【解决方案1】:

Golub 和 Van Loan 的“矩阵计算”一书概述了一种可行的寻址方案:

您将数据打包到一个向量中并按如下方式访问,假设 i >= j:

a_ij = A.vec((j-1)n - j(j-1)/2 + i)    

【讨论】:

    【解决方案2】:

    您可能最好使用一个完整的方形 numpy 矩阵。是的,它浪费了一半的内存来存储冗余值,但是在 Python 中滚动你自己的对称矩阵将通过将整数存储和处理为 Python 对象来浪费更多的内存和 CPU。

    【讨论】:

      【解决方案3】:

      一种更简单、更简洁的方法是使用带有排序元组的字典作为键。元组与您的矩阵索引相对应。覆盖 __getitem____setitem__ 以通过排序的元组访问字典;这是一个示例类:

      class Matrix(dict):
          def __getitem__(self, index):
              return super(Matrix, self).__getitem__(tuple(sorted(index)))
          def __setitem__(self, index, value):
              return super(Matrix, self).__setitem__(tuple(sorted(index)), value)
      

      然后像这样使用它:

      >>> matrix = Matrix()
      >>> matrix[2,3] = 1066
      >>> print matrix
      {(2, 3): 1066}
      >>> matrix[2,3]
      1066
      >>> matrix[3,2]
      1066
      >>> matrix[1,1]
      Traceback (most recent call last):
        File "<stdin>", line 1, in ?
        File "z.py", line 3, in __getitem__
          return super(Matrix, self).__getitem__(tuple(sorted(index)))
      KeyError: (1, 1)
      

      【讨论】:

        【解决方案4】:

        您只需要存储矩阵的下三角形。通常这是通过一个 n(n+1)/2 长度的列表来完成的。您需要重载 __getitem__ 方法来解释条目的含义。

        【讨论】:

          猜你喜欢
          • 2011-12-24
          • 2018-03-26
          • 2011-06-20
          • 1970-01-01
          • 2013-10-18
          • 2016-10-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多