Numpy `Diagflat` for Specified Axis

Numpy `Diagflat` for Specified Axis

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?

3

1 Answer

Simply do:

example[..., np.newaxis] * Id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.