slicing a matrix in python vs matlab

Question:

After being a MATLAB user for many years, I am now migrating to python.

I try to find a concise manner to simply rewrite the following MATLAB code in python:

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

where Mtx is a 2D sparse matrix

My python solution is:

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

The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly?

Thanks!

Asked By: Yuval Atzmon

||

Answers:

Try doing this instead:

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

Source: Link

It’s less obfuscated compared to your version, but according to the guide, this is the best you’ll get!

Answered By: rayryeng

Found a concise answer, thanks to the lead of rayryeng:

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

another alternative is:

s = Mtx.sum(0)
newMtx = Mtx[:,(s.A > 0)[0]]
Answered By: Yuval Atzmon

Try using find to get the row and col index matching the find criteria

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])
Answered By: Golden Lion
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.