Matrix slicing in python vs matlab

As a MATLAB user for many years, I am now switching to python.

I am trying to find a brief way to simply rewrite the following MATLAB code in python:

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

where Mtx is a two-dimensional sparse matrix

My python solution:

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

where Mtx is the sparse 2D CSC matrix

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

Thank!

+4
source share
2 answers

Found a short answer thanks to the leadership of Rayryeng:

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

another variant:

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

Try to do this instead:

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

Source: http://wiki.scipy.org/NumPy_for_Matlab_Users#head-13d7391dd7e2c57d293809cff080260b46d8e664

, , , , !

+1

Source: https://habr.com/ru/post/1541045/


All Articles