manan manan - 1 year ago 91
Python Question

MATLAB "any" conditional deletion translation to Python

I'm having trouble understanding what

B = A(~any(A < threshold, 2), :);
(in MATLAB) does given array
with dimensions N x 3.

Ultimately, I am trying to implement a function do perform the same operation in Python (so far, I have something like
B = A[not any(A[:,1] < threshold), :]
, which I know to be incorrect), and I was wondering what the numpy equivalent to such an operation would be.

Thank you!

Answer Source

Not much of difference really. In MATLAB, you are performing ANY along the rows with any(...,2). In NumPy, you have axis to denote those dimensions and for a 2D array, it would be np.any(...,axis=1).

Thus, the NumPy equivalent implementation would be -

import numpy as np

B = A[~np.any(A < threshold,axis=1),:]

This indexing is also termed as slicing in NumPy terminology. Since, we are slicing along the first axis, we can drop the all-elements-selection along the rest of the axes. So, it would simplify to -

B = A[~np.any(A < threshold,axis=1)]

Finally, we can use the method ndarray.any and skip the mention of axis parameter to shorten the code further, like so -

B = A[~(A < threshold).any(1)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download