Skip to content

Commit

Permalink
Overload UniformScaling to make I(n) create a Diagonal matrix.
Browse files Browse the repository at this point in the history
Fixes #23156
  • Loading branch information
andreasnoack committed Dec 7, 2018
1 parent 1875947 commit b103c35
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ Standard library changes
* `mul!`, `rmul!` and `lmul!` methods for `UniformScaling` ([#29506]).
* `Symmetric` and `Hermitian` matrices now preserve the wrapper when scaled with a number ([#29469]).
* Exponentiation operator `^` now supports raising a `Irrational` to an `AbstractMatrix` power ([#29782]).
* `UniformScaling` instances are now callable such that e.g. `I(3)` will produce a `Diagonal` matrix ([#30298]).

#### Random
* `randperm` and `randcycle` now use the type of their argument to determine the element type of
Expand Down
25 changes: 25 additions & 0 deletions stdlib/LinearAlgebra/src/uniformscaling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,31 @@ julia> [1 2im 3; 1im 2 3] * I
"""
const I = UniformScaling(true)

"""
(J::UniformScaling)(n::Integer)
Construct a `Diagonal` matrix from a `UniformScaling`.
!!! compat "Julia 1.1"
This method is available as of Julia 1.1.
# Examples
```jldoctest
julia> I(3)
3×3 Diagonal{Bool,Array{Bool,1}}:
true ⋅ ⋅
⋅ true ⋅
⋅ ⋅ true
julia> (0.7*I)(3)
3×3 Diagonal{Float64,Array{Float64,1}}:
0.7 ⋅ ⋅
⋅ 0.7 ⋅
⋅ ⋅ 0.7
```
"""
(J::UniformScaling)(n::Integer) = Diagonal(fill(J.λ, n))

eltype(::Type{UniformScaling{T}}) where {T} = T
ndims(J::UniformScaling) = 2
Base.has_offset_axes(::UniformScaling) = false
Expand Down
5 changes: 5 additions & 0 deletions stdlib/LinearAlgebra/test/uniformscaling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -299,4 +299,9 @@ end
@test rmul!(copyto!(C, A), J) == target
end

@testset "Construct Diagonal from UniformScaling" begin
@test size(I(3)) === (3,3)
@test I(3) isa Diagonal
end

end # module TestUniformscaling

0 comments on commit b103c35

Please sign in to comment.