scipy.io.
mmwrite#
- scipy.io.mmwrite(target, a, comment=None, field=None, precision=None, symmetry='AUTO')[source]#
将稀疏或密集数组 a 写入 Matrix Market 文件类 target。
- 参数:
- targetstr 或 file-like
矩阵市场文件名(扩展名 .mtx)或打开的文件类对象。
- aarray like
稀疏或稠密 2-D 数组。
- commentstr, 可选
要添加到矩阵市场文件的注释。
- fieldNone 或 str, 可选
可以是 ‘real’、‘complex’、‘pattern’ 或 ‘integer’。
- precisionNone 或 int, 可选
用于实数或复数值显示的数字位数。
- symmetryNone 或 str, 可选
可以是 ‘AUTO’、‘general’、‘symmetric’、‘skew-symmetric’ 或 ‘hermitian’。如果 symmetry 为 None,则 ‘a’ 的对称类型由其值确定。如果 symmetry 为 ‘AUTO’,则 ‘a’ 的对称类型由 mmwrite自行确定或设置为 ‘general’。
- 返回:
- None
附注
更改于版本 1.12.0: C++ 实现。
示例
>>> from io import BytesIO >>> import numpy as np >>> from scipy.sparse import coo_array >>> from scipy.io import mmwrite
将一个小 NumPy 数组写入矩阵市场文件。文件将以
'array'格式写入。>>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]]) >>> target = BytesIO() >>> mmwrite(target, a) >>> print(target.getvalue().decode('latin1')) %%MatrixMarket matrix array real general % 2 4 1 0 0 2.5 0 0 0 6.25
添加注释到输出文件,并将精度设置为 3。
>>> target = BytesIO() >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3) >>> print(target.getvalue().decode('latin1')) %%MatrixMarket matrix array real general % % Some test data. % 2 4 1.00e+00 0.00e+00 0.00e+00 2.50e+00 0.00e+00 0.00e+00 0.00e+00 6.25e+00
在调用
mmwrite之前转换为稀疏矩阵。这将导致输出格式为'coordinate'而不是'array'。>>> target = BytesIO() >>> mmwrite(target, coo_array(a), precision=3) >>> print(target.getvalue().decode('latin1')) %%MatrixMarket matrix coordinate real general % 2 4 3 1 1 1.00e+00 2 2 2.50e+00 2 4 6.25e+00
将复数 Hermite 数组写入矩阵市场文件。请注意,实际上只有六个值被写入文件;其他值由对称性隐含。
>>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]]) >>> z array([[ 3. +0.j, 1. +2.j, 4. -3.j], [ 1. -2.j, 1. +0.j, -0. -5.j], [ 4. +3.j, 0. +5.j, 2.5+0.j]])
>>> target = BytesIO() >>> mmwrite(target, z, precision=2) >>> print(target.getvalue().decode('latin1')) %%MatrixMarket matrix array complex hermitian % 3 3 3.0e+00 0.0e+00 1.0e+00 -2.0e+00 4.0e+00 3.0e+00 1.0e+00 0.0e+00 0.0e+00 5.0e+00 2.5e+00 0.0e+00
此方法是线程化的。默认线程数等于系统中的 CPU 数量。使用 threadpoolctl 来覆盖
>>> import threadpoolctl >>> >>> target = BytesIO() >>> with threadpoolctl.threadpool_limits(limits=2): ... mmwrite(target, a)