manan - 1 year ago 55

Python Question

I'm having trouble understanding what

`B = A(~any(A < threshold, 2), :);`

`A`

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), :]`

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)]
```