Stream: helpdesk (published)

Topic: Should `diag(x::Number) = x` be defined?


view this post on Zulip Júlio Hoffimann (Jan 17 2025 at 21:45):

I am writing n-dimensional algorithms and it would be convenient to call this function with either numbers or matrices.

view this post on Zulip Júlio Hoffimann (Jan 17 2025 at 21:47):

Could this method be added to Base? Any counter-argument?

view this post on Zulip jar (Jan 17 2025 at 21:50):

If you're working on n-dimensional arrays and you need to support the n=0 case, Julia has a 0-dimensional array type Array{T, 0}:

julia> fill(4)
0-dimensional Array{Int64, 0}:
4

that might work for your application.

view this post on Zulip Júlio Hoffimann (Jan 17 2025 at 22:07):

Would it have the same performance benefits of a Number though? Stack allocation?

view this post on Zulip Júlio Hoffimann (Jan 17 2025 at 22:07):

Ideally the algorithm would retain its performance with Number inputs

view this post on Zulip Fredrik Bagge Carlson (Jan 20 2025 at 19:26):

mydiag(x::AbstractArray) = diag(x)
mydiag(x::Number) = x

view this post on Zulip Júlio Hoffimann (Jan 20 2025 at 19:30):

Yes. My question is if there is a problem in defining this in Base?

view this post on Zulip Mason Protter (Jan 20 2025 at 19:44):

I don't really see why we'd put this in base. I think it'd be better to just define your own mydiag like Fredrik showed

view this post on Zulip Júlio Hoffimann (Jan 20 2025 at 19:53):

Mathematically speaking, doesn't it make sense to extend the method?

view this post on Zulip Júlio Hoffimann (Jan 20 2025 at 19:55):

I've seen Number used in places that expect matrices or vectors as inputs.

view this post on Zulip Mason Protter (Jan 20 2025 at 20:19):

Numbers are not matrices or vectors. They're zero dimensional objects. diag is specifically defined on matrices

view this post on Zulip Júlio Hoffimann (Jan 20 2025 at 20:22):

I thought that numbers could be seen as linear algebras over themselves.

view this post on Zulip Júlio Hoffimann (Jan 20 2025 at 20:23):

In that case one can introduce a coord system and identify the number with itself. Consequently defining diag too

view this post on Zulip Júlio Hoffimann (Jan 20 2025 at 20:23):

But if people already see a problem with this on Zulip. The chances it gets accepted in Base are low


Last updated: Jan 29 2025 at 04:38 UTC