稀疏工具#
- sympy.matrices.sparsetools._doktocsr()[源代码]#
将稀疏矩阵转换为压缩稀疏行(CSR)格式。
- 参数:
A :包含按键(行、列)排序的非零元素
JA :是的 [i] 列是否对应于 [i]
IA :IA型 [i] 包含第一个非零元素的索引
行的 [i] . 因此IA [i+1] -IA公司 [i] 给出非零元素行数 [i] . IA的长度总是比矩阵中的行数多1。
实例
>>> from sympy.matrices.sparsetools import _doktocsr >>> from sympy import SparseMatrix, diag >>> m = SparseMatrix(diag(1, 2, 3)) >>> m[2, 0] = -1 >>> _doktocsr(m) [[1, 2, -1, 3], [0, 1, 0, 2], [0, 1, 2, 4], [3, 3]]
- sympy.matrices.sparsetools._csrtodok()[源代码]#
将CSR表示形式转换为DOK表示形式。
实例
>>> from sympy.matrices.sparsetools import _csrtodok >>> _csrtodok([[5, 8, 3, 6], [0, 1, 2, 1], [0, 0, 2, 3, 4], [4, 3]]) Matrix([ [0, 0, 0], [5, 8, 0], [0, 0, 3], [0, 6, 0]])
- sympy.matrices.sparsetools.banded(**kwargs)[源代码]#
从给定的字典中返回描述矩阵对角线的SparseMatrix。上对角线的键为正,主对角线下的键为负。这些值可以是:
表达式或单参数函数,
值的列表或元组,
矩阵
除非给出尺寸,否则返回矩阵的大小将足够大,以包含提供的最大非零值。
克沃斯
- 排结果矩阵的行;如果
不给。
- 科尔斯结果矩阵的列;如果
不给。
实例
>>> from sympy import banded, ones, Matrix >>> from sympy.abc import x
如果在元组中给出显式值,则矩阵将自动调整大小以包含所有值,否则将在整个对角线上填充单个值:
>>> banded({1: (1, 2, 3), -1: (4, 5, 6), 0: x}) Matrix([ [x, 1, 0, 0], [4, x, 2, 0], [0, 5, x, 3], [0, 0, 6, x]])
接受单个参数的函数可以用来填充对角线,作为对角线索引的函数(从0开始)。必须给出矩阵的大小(或形状)才能获得大于1x1的矩阵:
>>> s = lambda d: (1 + d)**2 >>> banded(5, {0: s, 2: s, -2: 2}) Matrix([ [1, 0, 1, 0, 0], [0, 4, 0, 4, 0], [2, 0, 9, 0, 9], [0, 2, 0, 16, 0], [0, 0, 2, 0, 25]])
放置在对角线上的矩阵对角线将与所示对角线重合:
>>> vert = Matrix([1, 2, 3]) >>> banded({0: vert}, cols=3) Matrix([ [1, 0, 0], [2, 1, 0], [3, 2, 1], [0, 3, 2], [0, 0, 3]])
>>> banded(4, {0: ones(2)}) Matrix([ [1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]])
如果指定的大小不能将所有值保存整数倍,则会引发错误。这里,行被指定为奇数(但是需要一个偶数来保持非对角线2x2行):
>>> banded({0: 2, 1: ones(2)}, rows=5) Traceback (most recent call last): ... ValueError: sequence does not fit an integral number of times in the matrix
在这里,行数是偶数……但是方阵也有偶数列。正如我们在前面的示例中看到的,需要一个奇数:
>>> banded(4, {0: 2, 1: ones(2)}) # trying to make 4x4 and cols must be odd Traceback (most recent call last): ... ValueError: sequence does not fit an integral number of times in the matrix
一种避免计算行数的方法是将矩阵元素封闭在元组中,并在右侧指示所需的行数:
>>> banded({0: 2, 2: (ones(2),)*3}) Matrix([ [2, 0, 1, 1, 0, 0, 0, 0], [0, 2, 1, 1, 0, 0, 0, 0], [0, 0, 2, 0, 1, 1, 0, 0], [0, 0, 0, 2, 1, 1, 0, 0], [0, 0, 0, 0, 2, 0, 1, 1], [0, 0, 0, 0, 0, 2, 1, 1]])
如果将多个值写入给定项,将引发错误。在这里,如果它们放在第一个对角线上,它们与主对角线重叠:
>>> banded({0: (2,)*5, 1: (ones(2),)*3}) Traceback (most recent call last): ... ValueError: collision at (1, 1)
通过将0放在2x2矩阵的左下角,可以避免碰撞:
>>> u2 = Matrix([ ... [1, 1], ... [0, 1]]) >>> banded({0: [2]*5, 1: [u2]*3}) Matrix([ [2, 1, 1, 0, 0, 0, 0], [0, 2, 1, 0, 0, 0, 0], [0, 0, 2, 1, 1, 0, 0], [0, 0, 0, 2, 1, 0, 0], [0, 0, 0, 0, 2, 1, 1], [0, 0, 0, 0, 0, 0, 1]])