Skip to content

Commit 7c955c4

Browse files
andreasnoackStefanKarpinski
authored andcommitted
Overload UniformScaling to make I(n) create a Diagonal matrix. (#30298)
Fixes #23156
1 parent 155c319 commit 7c955c4

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ Standard library changes
3333
#### LinearAlgebra
3434

3535
* Added keyword arguments `rtol`, `atol` to `pinv` and `nullspace` ([#29998]).
36+
* `UniformScaling` instances are now callable such that e.g. `I(3)` will produce a `Diagonal` matrix ([#30298]).
3637

3738
#### SparseArrays
3839

stdlib/LinearAlgebra/src/uniformscaling.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,31 @@ julia> [1 2im 3; 1im 2 3] * I
4848
"""
4949
const I = UniformScaling(true)
5050

51+
"""
52+
(I::UniformScaling)(n::Integer)
53+
54+
Construct a `Diagonal` matrix from a `UniformScaling`.
55+
56+
!!! compat "Julia 1.2"
57+
This method is available as of Julia 1.2.
58+
59+
# Examples
60+
```jldoctest
61+
julia> I(3)
62+
3×3 Diagonal{Bool,Array{Bool,1}}:
63+
1 ⋅ ⋅
64+
⋅ 1 ⋅
65+
⋅ ⋅ 1
66+
67+
julia> (0.7*I)(3)
68+
3×3 Diagonal{Float64,Array{Float64,1}}:
69+
0.7 ⋅ ⋅
70+
⋅ 0.7 ⋅
71+
⋅ ⋅ 0.7
72+
```
73+
"""
74+
(I::UniformScaling)(n::Integer) = Diagonal(fill(I.λ, n))
75+
5176
eltype(::Type{UniformScaling{T}}) where {T} = T
5277
ndims(J::UniformScaling) = 2
5378
Base.has_offset_axes(::UniformScaling) = false

stdlib/LinearAlgebra/test/uniformscaling.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,4 +309,10 @@ end
309309
@test rmul!(copyto!(C, A), J) == target
310310
end
311311

312+
@testset "Construct Diagonal from UniformScaling" begin
313+
@test size(I(3)) === (3,3)
314+
@test I(3) isa Diagonal
315+
@test I(3) == [1 0 0; 0 1 0; 0 0 1]
316+
end
317+
312318
end # module TestUniformscaling

0 commit comments

Comments
 (0)