0

I am working with matrices of (x,y,z) dimensions, and would like to index numerous values from this matrix simultaneously.

ie. if the index A[0,0,0] = 5

and A[1,1,1] = 10

A[[1,1,1], [5,5,5]] = [5, 10]

however indexing like this seems to return huge chunks of the matrix.

Does anyone know how I can accomplish this? I have a large array of indices (n, x, y, z) that i need to use to index from A)

Thanks

2 Answers 2

2

You are trying to use 1 as the first index 3 times and 5 as the index into the second dimension (again three times). This will give you the element at A[1,5,:] repeated three times.

A = np.random.rand(6,6,6);
B = A[[1,1,1], [5,5,5]]
# [[ 0.17135991,  0.80554887,  0.38614418,  0.55439258,  0.66504806,  0.33300839],
#  [ 0.17135991,  0.80554887,  0.38614418,  0.55439258,  0.66504806,  0.33300839],
#  [ 0.17135991,  0.80554887,  0.38614418,  0.55439258,  0.66504806,  0.33300839]]

B.shape
# (3, 6)

Instead, you will want to specify [1,5] for each axis of your matrix.

A[[1,5], [1,5], [1,5]] = [5, 10]
Sign up to request clarification or add additional context in comments.

Comments

1

Advanced indexing works like this:

A[I, J, K][n] == A[I[n], J[n], K[n]]

with A, I, J, and K all arrays. That's not the full, general rule, but it's what the rules simplify down to for what you need.

For example, if you want output[0] == A[0, 0, 0] and output[1] == A[1, 1, 1], then your I, J, and K arrays should look like np.array([0, 1]). Lists also work:

A[[0, 1], [0, 1], [0, 1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.