3

I am trying to create a three dimensional array, Tusing numpy defined as follows:

T_{i, j, k} = \delta_{i, k} - \delta{j, k}

where \delta_{i, j} is the Kronecker delta function (1 when i=j and 0 otherwise). I am wondering what the most efficient way to do this using numpy. I can create two three dimensional arrays using for loops and subtract them. But I suspect there is a quicker and more idiomatic method. Any help would be most appreciated.

1 Answer 1

6

The equivalent to delta is eye in numpy:

delta = numpy.eye(5)
T = delta[:,None,:] - delta[None,:,:]

The None creates a ‹virtual› dimension (doesn't take any additional memory) used for broadcasting in numpy.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Just so I can better understand this. Suppose I just wanted to create a three dimensional array X defined by X_{i, j, k} = X_{i, k} for all j. The first term in the above does not seem to do that as the first dimension must have length. How would I do that?
@gzc yes I think there is a typo. What we want is delta[:, None, :] - delta[None, :, :]

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.