Numpy/Scipy 中与Matlab中的sparse函数等效的操作——Python处理稀疏矩阵

创建稀疏矩阵 - MATLAB sparse - MathWorks 中国

python - numpy/scipy equivalent of MATLAB's sparse function - Stack Overflow
S = sparse(i,j,v,m,n) 将 S 的大小指定为 m×n。
等效的python操作是

import numpy as np
import scipy.sparse as sps

H = sps.csr_matrix((V, (I, J)), shape=(m,n),dtype= np.int32)

其中I向量(数组)记录非零元素行的位置,J向量(数组)表示非零元素列的位置,V向量表示非零元素值,(也可以指定其中部分元素为0),稀疏是一种存储优化方法,未必就是只保存非0元素。

m2 = sps.csr_matrix(([3,1], ([2,1], [2,3])), dtype=np.float)
m2.todense()

[3,1]两个非稀疏化元素,一个是3,一个是1
[2,1]记录了行位置,[2,3]记录了列位置,3在(2,2),1在(1,3)

matrix([[0., 0., 0., 0.],
        [0., 0., 0., 1.],
        [0., 0., 3., 0.]])
m2 = sps.csr_matrix(([3,0], ([2,1], [2,3])), dtype=np.float)
m2.todense()
matrix([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 3., 0.]])
原文地址:https://www.cnblogs.com/lingr7/p/12981972.html