如何获得稀疏复矩阵的元素绝对值?通常,是否可以使用用户定义的函数将矩阵映射到另一个矩阵?
答案 0 :(得分:1)
对我来说,以下工作正常
import numpy as np
from scipy import sparse
a = sparse.identity(5).tocsr() * 1j
a[2,4] = 1-1j
b = np.absolute(a)
b.A
# array([[ 1. , 0. , 0. , 0. , 0. ],
# [ 0. , 1. , 0. , 0. , 0. ],
# [ 0. , 0. , 1. , 0. , 1.41421356],
# [ 0. , 0. , 0. , 1. , 0. ],
# [ 0. , 0. , 0. , 0. , 1. ]])
# general functions: use the data attribute to access nonzeros
b.data = np.exp(b.data)
b.A
# array([[ 2.71828183, 0. , 0. , 0. , 0. ],
# [ 0. , 2.71828183, 0. , 0. , 0. ],
# [ 0. , 0. , 2.71828183, 0. , 4.11325038],
# [ 0. , 0. , 0. , 2.71828183, 0. ],
# [ 0. , 0. , 0. , 0. , 2.71828183]])
答案 1 :(得分:1)
scipy中的稀疏矩阵对象实现方法__abs__()
。这意味着您可以使用Python的内置 abs()
函数。它会将调用分派给__abs__()
方法。例如,
In [16]: from scipy.sparse import csr_matrix
In [17]: a = csr_matrix([[1+1j, 0, 0, 0], [0, -2, 0, 0], [0, 0, 0, 0], [3-4j, 0, -5j, 0]])
In [18]: a.A
Out[18]:
array([[ 1.+1.j, 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, -2.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
[ 3.-4.j, 0.+0.j, 0.-5.j, 0.+0.j]])
In [19]: b = abs(a)
In [20]: b.A
Out[20]:
array([[ 1.41421356, 0. , 0. , 0. ],
[ 0. , 2. , 0. , 0. ],
[ 0. , 0. , 0. , 0. ],
[ 5. , 0. , 5. , 0. ]])