Search code examples
pythonarraysnumpydiagonal

Access to short diagonal elements in Numpy 3 dimensional array


I have a 3 dimensional numpy array and I want to access short diagonal elements of it. Let's say i,j,k are three dimensions. Is it possible to access elements where i==j or i==k or j==k, so that I can set them to a specific value.

I tried to solve this by creating a mask variable of indices. This mask variable of indices is fed to the final array where the values of {i=j or i=k or j=k} are set to specific values. Unfortunately this code is returning the set where {i=j=k}

import numpy as np

N = 3

maskXY = np.eye(N).reshape(N,N,1)

maskYZ = np.eye(N).reshape(1,N,N)

maskXZ = np.eye(N).reshape(N,1,N)

maskIndices = maskXY * maskYZ*maskXZ

#set the values of final array using above mask

finalArray[maskIndices] = #specific values

Solution

  • Approach #1

    We could create open meshes with np.ix_ using the ranged arrays covering the dimensions of the input array and then perform OR-ing among those with a very close syntax to the one described in the question, like so -

    i,j,k = np.ix_(*[np.arange(r) for r in finalArray.shape])
    mask = (i==j) | (i==k) | (j==k)
    finalArray[mask] = # desired values
    

    Approach #2

    It seems, we can also follow the posted code in the question and use boolean versions of the masks and then perform OR-ing to get the mask equivalent, like so -

    mask = (maskXY==1) | (maskYZ==1) | (maskXZ==1)
    

    But, this involves masks that are 2D (when squeezed) and as such won't be as memory-efficient as the previous approach that dealt with 1D arrays.