python - 如何找到二维矩阵的两条对角线?

标签 python numpy math matrix

<分区>

假设有一个 3 行 3 列的 numpy 矩阵。找到第一条对角线很容易,这是一种方法。

具有以下矩阵:

[[0,3,6]

 [0,4,9]

 [0,1,9]]

使用这段代码:

import numpy
matrix.diagonals()
[0, 4, 9]

如何得到相反的对角线?例如,对于上面的矩阵,我希望它返回:

[6, 4, 0]

最佳答案

实现这一目标的最快方法是使用步幅。您的数组有一个 .strides 属性,它告诉您必须在内存中向前跳过多少字节才能到达每个维度中的下一个项目:

>>> a = np.array([[0, 3, 6], [0, 4, 9], [0, 1, 9]])
>>> a.strides
(24, 8)

对于正常的正向对角线,您必须向前跳过一行加一列,对于反向对角线,您必须向前跳过一行减去一列:

>>> a.strides[0] + a.strides[1]
32
>>> a.strides[0] - a.strides[1]
16

您现在可以 construct来自与原始数组相同的内存缓冲区的数组,但具有新的步幅(以及在反向对角线情况下从第一行的最后一列开始的非零偏移量):

>>> np.ndarray(shape=min(a.shape), dtype=a.dtype, buffer=a, 
...            offset=0, strides=a.strides[0]+a.strides[1])
array([0, 4, 9])
>>> np.ndarray(shape=min(a.shape), dtype=a.dtype, buffer=a, 
...            offset=a.strides[1] * (a.shape[1] - 1),
...            strides=a.strides[0]+a.strides[1])
array([6, 4, 0])

这些实际上是原始数组内存的 View ,也就是说,如果你修改它们的内容,原始数组也会改变,所以实际上没有内存分配或复制正在进行,只是包含对象的设置,所以它会尽可能快。

关于python - 如何找到二维矩阵的两条对角线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769975/

相关文章:

python - 创建 Python 包时出现问题

python - 如何启动 pdb 并从 REPL 进入函数?

python - 从 Python 3.7 conda 环境中在 Spyder 下导入 numpy 时出现 ImportError

python - 安装numpy,仍然有问题

python - '类型错误 : an integer is required' when initializing random weight matrix in numpy with numpy. random.randn()

r - fft 输出的实部和虚部是否相关?

python - 删除空格时的正则表达式匹配,如何从带空格的原始字符串中删除匹配的字符?

python - 将数据帧拆分为多个数据帧

algorithm - 您可以通过几种方式在BST中插入一系列值以形成特定的树?

math - 分数长度