0

Suppose I have an N x N x N dimensional numpy array X with entries X[i,j,k]. I want to use X to define an N x N x N x N dimensional numpy array Y defined as follows:

Y[i,j,k,k] = X[i,j,k]
Y[i,j,k,l] = 0 when k != l

My idea is to use numpy.einsum to accomplish this task via the following code:

Y = np.einsum('ijk->ijkk', X).

However, this doesn't work since I get the following error

ValueError: einstein sum subscripts string includes output subscript 'k' multiple times

Is there a way to accomplish this straightforwardly without having to use for loops?

2
  • 1
    Why do you think einsum can do this? Just because 'ii->i' takes a diagonal, you think the "reverse" can add one? Is that documented? Commented Mar 9, 2023 at 20:12
  • If Y is a 4d array of the right shape, then z=np.einsum('ijkk->ijk',Y) is a 3d view. You could copy your X to that. Commented Mar 9, 2023 at 21:00

1 Answer 1

0

You can use einsum to extract a diagonal as you said. You will get a view of the original array, meaning if you modify the view, you will also modify the original array. This lets you overwrite the entries of the original array just like so:

# setup
import numpy as np
X = np.arange(0, 3*4*5).reshape((3, 4, 5))  # bogus data
Y = np.zeros((3, 4, 5, 5))                  # initialize Y with zeros

# extract diagonal, and write into it
Y_diag_view = np.einsum('ijkk->ijk', Y)
Y_diag_view[...] = X                        # modify Y_diag_view and therefore X in place
print(Y[0, 0, ...])                         # prints diagonal matrix
Sign up to request clarification or add additional context in comments.

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.