对于此矩阵,K =
[[-1. 1. 0.]
[ 0. 0. 0.]
[ 0. -1. 1.]
[ 0. 0. 0.]
[ 0. -1. 1.]
[ 0. 0. 0.]]
任务是将非零唯一行的索引存储在数组中(此处答案为{0,2}),以便
K([0,2],:)
可用于线性代数运算.
我的尝试是:
myList = []
for i in range(len(K)): #generate pairs
for j in range(i+1,len(K)): #travel down each other rows
if np.array_equal(K[i],K[j]) and np.any(K[i] != 0, axis=1) and np.any(K[j] != 0, axis=1):
myList.append(K[i])
print ('indices of similar-non-zeros rows are
',(i, j)),
elif not np.array_equal(K[i],K[j]) and np.any(K[i] != 0,axis=1) and np.any(K[j] != 0, axis=1):
myList.append(K[i])
print ('indices of non-similar-non-zeros rows are
',(i, j)),
else:
continue
new_K = np.asmatrix(np.asarray(myList))
new_new_K = np.unique(new_K,axis=0)
print('Now K is
',new_new_K)
答案是:
new_new_K = [[-1. 1. 0.]
[ 0. -1. 1.]]
问题1:如何以pythonic方式进行操作.以上是具有矩阵存储限制的替代解决方案,但将索引存储在数组中更为可取.