python - 仅将 sympy 矩阵的上三角值从 numpy.triu() 复制到数组中?

标签 python numpy sympy

我有一个方阵 A(可以是任意大小),我想取上三角部分并将这些值放在一个数组中,而中心对角线 (k=0) 以下的值不包含在内。

A = sympy.Matrix([[ 4,  0,  3],
                  [ 2,  4, -2],
                  [-2, -3,  7]])

使用 A_upper = numpy.triu(A) 让我可以

A_Upper = sympy.Matrix([[ 4,  0,  3],
                        [ 0,  4, -2],
                        [ 0,  0,  7]])

但是从这里我如何只将上三角元素复制到一个简单的数组中?如:

[4, 0, 3, 4, -2, 7]

我打算只是迭代并复制所有非零元素,但是允许上三角中的零。

最佳答案

给一个 numpy 数组,这是一个使用 numpy.triu_indices(N, k=0) 的简单操作,其中 N 是方形数组的大小:

In [28]: B = np.array([[4, 0, 3], [2, 4, -2], [-2, -3, 7]])

In [29]: B[np.triu_indices(B.shape[0])]
Out[29]: array([ 4,  0,  3,  4, -2,  7])

B.shape[0] 就在那里,以防您不想硬编码数组 (3) 的大小。


给定一个 sympy 矩阵,这不是那么容易,但已经足够接近了。只需转换为一个 numpy 数组,并确保将 dtypeobject 更改。如果您的矩阵大小合理,这应该会很好地工作。如果它们变得非常大,您可能需要重新考虑这一点。

In [36]: A = sp.Matrix([[4, 0, 3], [2, 4, -2], [-2, -3, 7]])

# you can change the dtype of the new array to match the first array
# e.g., .astype(int), .astype(sp.Symbol)
# or you can just leave the default (dtype=object)
In [37]: C = np.array(A) #.astype(new_dtype) 

In [38]: C[np.triu_indices(C.shape[0])]
Out[38]: array([ 4,  0,  3,  4, -2,  7])

要将它们放入一个普通列表中,请执行

In [39]: C[np.triu_indices(C.shape[0])].tolist()
Out[39]: [4, 0, 3, 4, -2, 7]

关于python - 仅将 sympy 矩阵的上三角值从 numpy.triu() 复制到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647643/

相关文章:

python - 如何通过生成器或其他方式在 Python 中无限循环迭代器?

python - 理解 pandas 中的 lambda 函数

python - 难道 `sympy` 比 Mathematica 慢得多吗?

python - NumPy C API : Link several object files

python - 使 bytearray 的 memoryview 在 Python 2.7 中返回 int 元素

Python 特征向量 : differences among numpy. linalg、scipy.linalg 和 scipy.sparse.linalg

python - 如何生成粉红噪声图像?

python - 3D 数组中的索引列表

python - sympy 中的矩阵列表/数组

python - sympy 解析器未将 expm1 识别为符号函数