user861537
user861537

Reputation:

Indexing numpy arrays with different number of dimensions

I am using numpy and I want to store the result of a calculation inside a three or four-dimensional matrix. I want to do something like this:

result[:, indices, iteration] = some_function()  # won't work

where the dimension is understood from the length of the indices tuple. So if indices equals, say, (6,) or (8, 5) then I want to have the equivalent of

result[:, 6, iteration] = some_function()

or

result[:, 8, 5, iteration] = some_function()

Normally I'd put all of the coordinates into a tuple and use that as an index, but the presence of : prevents me from doing that.

The dimension of result has been set earlier to the correct dimension, so can check it, but it would be nice to only use the length of indices to determine it. Is there some way to accomplish this?

Upvotes: 1

Views: 139

Answers (2)

wim
wim

Reputation: 362517

Try using result[(slice(None),) + indices + (iteration,)]

Upvotes: 1

Louis
Louis

Reputation: 2890

If you need to know the length of indices :

len(indices)

But is it this your question ?

Upvotes: 1

Related Questions