-
Notifications
You must be signed in to change notification settings - Fork 50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is there a way to create a diagonal array? #733
Comments
(Probably niche.) |
It is fairly niche, but still an interesting question. It may be in the category of "should be implementable given the primitives in the standard". And I think it is, given there's >>> def create_diagonal(values):
... """The 2-D version only, should be generalizable"""
... n = values.shape[0]
... x = xp.zeros(n**2, dtype=values.dtype)
... x[::n+1] = values
... return xp.reshape(x, (n, n))
...
>>> values = xp.asarray([0, 1, 2, 3, 9.5])
>>> create_diagonal(values)
array([[0. , 0. , 0. , 0. , 0. ],
[0. , 1. , 0. , 0. , 0. ],
[0. , 0. , 2. , 0. , 0. ],
[0. , 0. , 0. , 3. , 0. ],
[0. , 0. , 0. , 0. , 9.5]]) It's vectorized, so this should be fine performance-wise too. To check: >>> values = xp.asarray([0, 1, 2, 3, 9.5] * 1000)
>>> values.shape
(5000,)
>>> %timeit create_diagonal(values)
4.62 ms ± 69.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit np.diag(values)
4.61 ms ± 43.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
|
Also, gh-403 contains the following comment:
(that is |
Thank you very much for taking the time to write this! I also agree with you about |
In gh-668 there's a very basic start to a guide to answer such questions. This probably fits in there, although it's not a one-liner translation. The other thing I had in mind is that it'd be nice to have reusable pure Python functions like this in a separate package - a la |
+1 on a separate package rather than expanding the scope of A related point is Robert's suggestion from the scipy linalg discussion:
Related in the sense that I think it's beyond the scope of array-api-compat. |
Something like:
I noticed that the array API has no way to do this in either batched or unbatched mode?
The text was updated successfully, but these errors were encountered: