访问 coo_matrix 中的元素 [英] Accessing elements in coo_matrix

查看:142
本文介绍了访问 coo_matrix 中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题.对于像 coo_matrix 这样的 SciPy 稀疏矩阵,如何访问单个元素?

以 Eigen 线性代数库为例.可以使用 coeffRef 访问元素 (i,j),如下所示:

myMatrix.coeffRef(i,j)

解决方案

来自 coo_matrix 的文档:

<代码> |预期用途|- COO 是一种构建稀疏矩阵的快速格式|- 构建矩阵后,转换为 CSR 或|用于快速算术和矩阵向量运算的 CSC 格式|- 默认情况下,转换为 CSR 或 CSC 格式时,重复 (i,j)|条目将汇总在一起.这有利于高效|有限元矩阵的构造等.(见示例)

事实上,csr_matrix 以预期的方式支持索引:

<预><代码>>>>从 scipy.sparse 导入 coo_matrix>>>m = coo_matrix([[1, 2, 3], [4, 5, 6]])>>>m1 = m.tocsr()>>>m1[1, 2]6>>>米1<2x3 稀疏矩阵的类型 '<type 'numpy.int64'>'具有 6 个以压缩稀疏行格式存储的元素>

(我从文档中找到上述引用的方式是 >>>> help(m) 相当于 在线文档).

This is a very simple question. For SciPy sparse matrices like coo_matrix, how does one access individual elements?

To give an analogy to Eigen linear algebra library. One can access element (i,j) using coeffRef as follows:

myMatrix.coeffRef(i,j)

解决方案

From the docs for coo_matrix:

 |  Intended Usage
 |      - COO is a fast format for constructing sparse matrices
 |      - Once a matrix has been constructed, convert to CSR or
 |        CSC format for fast arithmetic and matrix vector operations
 |      - By default when converting to CSR or CSC format, duplicate (i,j)
 |        entries will be summed together.  This facilitates efficient
 |        construction of finite element matrices and the like. (see example)

And indeed, csr_matrix supports the indexing in an expected way:

>>> from scipy.sparse import coo_matrix
>>> m = coo_matrix([[1, 2, 3], [4, 5, 6]])
>>> m1 = m.tocsr()
>>> m1[1, 2]
6
>>> m1
<2x3 sparse matrix of type '<type 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>

(The way I found the above quote from the docs was >>> help(m) which is equivalent to the online docs).

这篇关于访问 coo_matrix 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆