python怎么定义空矩阵_Python创建一个空的稀疏矩阵

我试图将一些真实数据解析为一个.mat对象,以便在我的

matlab脚本中加载.

我收到此错误:

TypeError: ‘coo_matrix’ object does not support item assignment

我找到了coo_matrix.但是,我无法为其分配值.

data.txt中

10 45

11 12

4 1

我想得到一个大小为100×100的稀疏矩阵.并指定1

Mat(10, 45) = 1

Mat(11, 12) = 1

Mat(4, 1) = 1

import numpy as np

from scipy.sparse import coo_matrix

def pdata(pathToFile):

M = coo_matrix(100, 100)

with open(pathToFile) as f:

for line in f:

s = line.split()

x, y = [int(v) for v in s]

M[x, y] = 1

return M

if __name__ == "__main__":

M = pdata('small.txt')

有什么建议吗?

最佳答案 使用coo_matrix构造此矩阵,使用(data,(rows,cols))`参数格式:

In [2]: from scipy import sparse

In [3]: from scipy import io

In [4]: data=np.array([[10,45],[11,12],[4,1]])

In [5]: data

Out[5]:

array([[10, 45],

[11, 12],

[ 4, 1]])

In [6]: rows = data[:,0]

In [7]: cols = data[:,1]

In [8]: data = np.ones(rows.shape, dtype=int)

In [9]: M = sparse.coo_matrix((data, (rows, cols)), shape=(100,100))

In [10]: M

Out[10]:

<100x100 sparse matrix of type ''

with 3 stored elements in COOrdinate format>

In [11]: print(M)

(10, 45) 1

(11, 12) 1

(4, 1) 1

如果将其保存为.mat文件以便在MATLAB中使用,它将以csc格式保存(已将其从库中转换):

In [13]: io.savemat('test.mat',{'M':M})

In [14]: d = io.loadmat('test.mat')

In [15]: d

Out[15]:

{'M': <100x100 sparse matrix of type ''

with 3 stored elements in Compressed Sparse Column format>,

'__globals__': [],

'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Mon Aug 7 08:45:12 2017',

'__version__': '1.0'}

coo格式不实现项目分配. csr和csc确实实现了它,但会抱怨.但它们是计算的常规格式. lil和dok是迭代赋值的最佳格式.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值