简体   繁体   English

在 python 和 matlab 中对矩阵进行切片

[英]slicing a matrix in python vs matlab

After being a MATLAB user for many years, I am now migrating to python.做了多年MATLAB的用户,现在迁移到python。

I try to find a concise manner to simply rewrite the following MATLAB code in python:我试图找到一种简洁的方式来简单地在python中重写以下MATLAB代码:

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

where Mtx is a 2D sparse matrix其中 Mtx 是二维稀疏矩阵

My python solution is:我的python解决方案是:

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

where Mtx is a 2D CSC sparse matrix其中 Mtx 是二维 CSC 稀疏矩阵

The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? python 代码不像 matlab 那样可读/优雅。知道如何更优雅地编写它吗?

Thanks!谢谢!

Try doing this instead: 尝试这样做:

s = Mtx.sum(0);
newMtx = Mtx[:,nonzero(s.T > 0)[0]] 

Source: http://wiki.scipy.org/NumPy_for_Matlab_Users#head-13d7391dd7e2c57d293809cff080260b46d8e664 资料来源: http//wiki.scipy.org/NumPy_for_Matlab_Users#head-13d7391dd7e2c57d293809cff080260b46d8e664

It's less obfuscated compared to your version, but according to the guide, this is the best you'll get! 与您的版本相比,它不那么模糊,但根据指南,这是您将获得的最好的!

Found a concise answer, thanks to the lead of rayryeng: 发现一个简明的答案,感谢rayryeng的领导:

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

another alternative is: 另一种选择是:

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

Try using find to get the row and col index matching the find criteria尝试使用 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM