2

I want a submatrix from a n-dimensional matrix. Without knowing in advance the dimensionality of the matrix. So given:

import random

a = [10 for _ in range(0, random.randint(0,10))]
M = np.full(a, True)
# Now get the submatrix dynamically with block notation
# so something like:
# str = ["1:5" for _ in range(0, len(a))].join(",")
# N = eval("M[ " + str + "]")

I would like to know of a nice way to do this notation wise and also speed wise.

(The other answer supplied in Numpy extract submatrix does not directly solve the question, because the accepted answer, using .ix_ does not accept a slice.)

levilime
  • 362
  • 1
  • 9

2 Answers2

2

We can use np.s_ that uses slice notation under the hoods -

M[[np.s_[1:5]]*M.ndim]

This gives us a FutureWarning :

FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated

To avoid it, we need to wrap with with tuple(), like so -

M[tuple([np.s_[1:5]]*M.ndim)]

Using the explicit slice notation, it would be -

M[tuple([slice(1,5)]*M.ndim)]
Divakar
  • 218,885
  • 19
  • 262
  • 358
1

With the nice stack overflow related search option I have already seen np.ix_, Numpy extract submatrix, then it would become:

N = M[np.ix_(*[range(1,5) for _ in range(0, len(a))])]
levilime
  • 362
  • 1
  • 9
  • This one throws `ValueError: Cross index must be 1 dimensional` for me. – Divakar Feb 28 '19 at 13:44
  • 1
    Yeah, I forgot the * so the elements of the list are unpacked as arguments for the function, so it becomes: `M[np.ix_(*[[1,5] for _ in range(0, len(a))])]` – levilime Feb 28 '19 at 15:01