I want to expand the axis of a ndarray to a diagonal matrix in the fashion of diagflat
E.g.
In [ ]: import numpy as np In [ ]: example = np.random.random((200, 5)) In [ ]: example.shape Out[ ]: (200, 5) What I am looking for, is something like:
In [ ]: np.diagflat(example, axis=-1).shape Out[ ]: (200, 5, 5) diagflat has however axis argument. My idea was the to simply insert a new axis in for example and multiply it with a unit matrix.
In [ ]: Id = np.eye(example.shape[-1]) In [ ]: (example[..., np.newaxis] @ Id).shape ValueError: shapes (200,5,1) and (5,5) not aligned: 1 (dim 2) != 5 (dim 0) This raises however an error, apparently broadcasting is not applied for matrix multiplications. Is there an elegant solution, or do I have to create and fill the array by hand?
31 Answer
Simply do:
example[..., np.newaxis] * Id