I am trying to fill a 3D NumPy array with the values of a 2D array using the numpy.fill_diagonal function. Both arrays have the same number of rows and columns. However, it results in an error ValueError: All dimensions of input must be of equal length
Below is an example of what I tried to do and what I am expecting to have
A = [[[0 1 1 1]
[1 0 1 1]
[1 1 0 1]
[1 1 1 0]]
[[0 1 1 1]
[1 0 1 1]
[1 1 0 1]
[1 1 1 0]]]
B = [[1 4 2 3]
[3 1 4 2]]
# Actual array shapes
A.shape (35,4,4)
B.shape (35,4)
numpy.fill_diagonal(A, B)
Expected result:
[[[1 1 1 1]
[1 4 1 1]
[1 1 2 1]
[1 1 1 3]]
[[3 1 1 1]
[1 1 1 1]
[1 1 4 1]
[1 1 1 2]]]
I have tried to reshape the 2D array to a 3D shape as follows
numpy.fill_diagonal(A, B[:,:,numpy.newaxis])
But I still got the same error
fill_diagonaltalks about usingdiag_indices. Specificallynp.diag_indices(3,ndim=3)produces the 3d indices for the 3 diag values that it sets.Instead let's get the 2d indices:
Then with a 3d array:
selects a (3,3) block. Then setting them with a (3,3):
That's the diagonal filling pattern you want.
Read the docs of functions like
fill_diagonalcarefully. And if there are confusing bits, see it's written in Python, so you can better figure out what it's doing.