在 SymPy 中分配矩阵切片
Assign Matrix slice in SymPy
我想在 SymPy 中替换矩阵的一部分的值。明确地说,它会像
import sympy as sym
A = sym.Matrix(4, 4, range(16))
A[0, :] = [-1, -2, -3, -4]
但这returns一个错误
ShapeError:
The Matrix `value` doesn't have the same dimensions as the in sub-
Matrix given by `key`.
在一个更有趣的例子中,我想做一些类似的事情
A[0, 0::2] = [-1, -2]
A[0, 1::2] = [1, 2]
交替奇数列和偶数列。
问题:在 SymPy 中有什么方法可以做到这一点吗?
SymPy 矩阵的切片与 NumPy 数组的工作方式不同:A[0, :]
是矩阵,而不是一维数组。正如 documentation 所说:
slices always give a matrix in return, even if the dimension is 1 x 1
因此必须相应地完成分配:
A[0, :] = [[-1, -2, -3, -4]] # a matrix with 1 row
A[:, 0] = [[-1], [-2], [-3], [-4]] # a matrix with 1 column
A[:, 0] = sym.Matrix([3, 4, 5, 6]) # easier way to create a one-column matrix
不幸的是,分配到非连续子矩阵如 A[0, 0::2]
没有(当前)实现:方法 copyin_matrix 假定分配的块是连续的。
我想在 SymPy 中替换矩阵的一部分的值。明确地说,它会像
import sympy as sym
A = sym.Matrix(4, 4, range(16))
A[0, :] = [-1, -2, -3, -4]
但这returns一个错误
ShapeError:
The Matrix `value` doesn't have the same dimensions as the in sub-
Matrix given by `key`.
在一个更有趣的例子中,我想做一些类似的事情
A[0, 0::2] = [-1, -2]
A[0, 1::2] = [1, 2]
交替奇数列和偶数列。
问题:在 SymPy 中有什么方法可以做到这一点吗?
SymPy 矩阵的切片与 NumPy 数组的工作方式不同:A[0, :]
是矩阵,而不是一维数组。正如 documentation 所说:
slices always give a matrix in return, even if the dimension is 1 x 1
因此必须相应地完成分配:
A[0, :] = [[-1, -2, -3, -4]] # a matrix with 1 row
A[:, 0] = [[-1], [-2], [-3], [-4]] # a matrix with 1 column
A[:, 0] = sym.Matrix([3, 4, 5, 6]) # easier way to create a one-column matrix
不幸的是,分配到非连续子矩阵如 A[0, 0::2]
没有(当前)实现:方法 copyin_matrix 假定分配的块是连续的。