# How to obtain the diagonal vector of a Diagonal matrix without allocations?

I want to obtain `D.diag` for a `Diagonal` matrix `D`, except I’m not sure if this is public. Using `diag(D)` allocates unnecessarily in certain cases (as it uses `similar` to ensure type-stability).

``````julia> D = Diagonal(3:4)
2×2 Diagonal{Int64, UnitRange{Int64}}:
3  ⋅
⋅  4

julia> diag(D)
2-element Vector{Int64}:
3
4

julia> D.diag
3:4

``````

How to I obtain the range back, given `D`, in a manner that is considered future-proof to include in a package?

Edit: I’ve found this hack that works, but I’m not sure if this is future-proof:

``````julia> eigvals(D)
3:4
``````

Evidently `parent` returns this

``````julia> parent(D)
3:4
``````
1 Like