在Python和Matlab中对矩阵进行切片的区别

5

我曾经是MATLAB的用户,现在正在转向Python。

我试图以简洁的方式重写以下MATLAB代码,将其转换为Python:

s = sum(Mtx);
newMtx = Mtx(:, s>0);

其中,Mtx是一个二维稀疏矩阵。

我的Python解决方案如下:

s = Mtx.sum(0)
newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices

Mtx是一个二维的CSC稀疏矩阵。

这段Python代码不如Matlab那么易读/优雅。有什么好的想法可以更加优雅地编写它吗?

谢谢!

3个回答

1
尝试使用这个替代方案:
s = Mtx.sum(0);
newMtx = Mtx[:,nonzero(s.T > 0)[0]] 

来源: 链接

与您的版本相比,它的混淆程度较低,但根据指南,这是您最好的选择!


太糟糕了,没有更简洁的了。 - Yuval Atzmon
嗨,这对我没用。原因是s是矩阵类型而不是数组类型。 - Yuval Atzmon
你没有告诉我你使用的是什么类型。从你的代码中,我假设你使用了向量/数组。好吧,很高兴你找到了它。顺便说一句,在发布之前你可以先搜索一下,这样可以节省一些带宽! - rayryeng

1

在rayryeng的帮助下,我找到了一个简明扼要的答案:

s = Mtx.sum(0)
newMtx = Mtx[:,(s.A1 > 0)]

另一个选择是:

s = Mtx.sum(0)
newMtx = Mtx[:,(s.A > 0)[0]]

0
尝试使用find函数获取与查找条件匹配的行和列索引。
import numpy as np
from scipy.sparse import csr_matrix
import scipy.sparse as sp
  
# Creating a 3 * 4 sparse matrix
sparseMatrix = csr_matrix((3, 4), 
                          dtype = np.int8).toarray()

sparseMatrix[0][0] = 1
sparseMatrix[0][1] = 2
sparseMatrix[0][2] = 3
sparseMatrix[0][3] = 4
sparseMatrix[1][0] = 5
sparseMatrix[1][1] = 6
sparseMatrix[1][2] = 7
sparseMatrix[1][3] = 8
sparseMatrix[2][0] = 9
sparseMatrix[2][1] = 10
sparseMatrix[2][2] = 11
sparseMatrix[2][3] = 12

# Print the sparse matrix
print(sparseMatrix)

B = sparseMatrix > 7 #the condition
row, col, data = sp.find(B)
print(row,col)
for a,b in zip(row,col):
    print(sparseMatrix[a][b])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接