我想从一个矩阵中得到三个向量,总结它的非零值。值向量、行索引向量和列索引向量
例如,如果W=[[0.2.0.],[0.10.0.],[0.0.5.]。 我希望函数返回([2.0,10.0,5.0],[0,1,2],[1,1,2])
下面的代码完成了这项工作,但对于大型矩阵来说太慢了。我的n是100000,我不知道哪些索引是非零的。有没有办法加快速度
from __future__ import division
import numpy as np
import collections
from numpy import *
import copy
#import timing
def nonZeroIndexes(W):
s = W.shape
nRows = s[0]
nColumns = s[1]
values = []
row_indexes = []
column_indexes = []
for r in xrange(nRows):
for c in xrange(nColumns):
if W[r,c] != 0:
values.append(W[r,c])
row_indexes.append(r)
column_indexes.append(c)
return values, row_indexes, column_indexes
n = 3
W = np.zeros((n,n))
W[0,1] = 2
W[1,1] = 10
W[2,2] = 5
vecs = nonZeroIndexes(W)
使用
np.nonzero
相关问题 更多 >
编程相关推荐