levilime
levilime

Reputation: 362

Dynamically get submatrix with numpy block(slice) notation

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.)

Upvotes: 2

Views: 446

Answers (2)

levilime
levilime

Reputation: 362

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

Upvotes: 1

Divakar
Divakar

Reputation: 221614

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

Upvotes: 2

Related Questions