Suppose I have an array like
mat = np.array([[1,1],[2,2],[3,3]])
which has shape (3,2). I want to create A new array with the shape (3,2,2) by taking the last axis of the array and create diagonal matrices out of it. I can do it with a for loop like
mat2 = np.zeros((3,2,2))
for i in np.arange(0,3):
mat2[i] = np.diag(mat[i])
which yields the desired output
[[[1. 0.]
[0. 1.]]
[[2. 0.]
[0. 2.]]
[[3. 0.]
[0. 3.]]]
But is there a way to do it in a direct vectorized (faster?!) version? In my real problem I have a large highly dimensional array of shape (...,n) and need to convert the last axis into a diagonal matrix with shape (...,n,n) in the end.