Skip to content

Commit

Permalink
Avoid copy in getindex(::AbstractQ, ...) (#44729)
Browse files Browse the repository at this point in the history
  • Loading branch information
dlfivefifty committed Mar 25, 2022
1 parent 68e2969 commit ea82910
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
5 changes: 3 additions & 2 deletions stdlib/LinearAlgebra/src/qr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -582,8 +582,9 @@ size(F::Union{QR,QRCompactWY,QRPivoted}) = size(getfield(F, :factors))
size(Q::AbstractQ, dim::Integer) = size(getfield(Q, :factors), dim == 2 ? 1 : dim)
size(Q::AbstractQ) = size(Q, 1), size(Q, 2)

copy(Q::AbstractQ{T}) where {T} = lmul!(Q, Matrix{T}(I, size(Q)))
getindex(Q::AbstractQ, inds...) = copy(Q)[inds...]
copymutable(Q::AbstractQ{T}) where {T} = lmul!(Q, Matrix{T}(I, size(Q)))
copy(Q::AbstractQ) = copymutable(Q)
getindex(Q::AbstractQ, inds...) = copymutable(Q)[inds...]
getindex(Q::AbstractQ, ::Colon, ::Colon) = copy(Q)

function getindex(Q::AbstractQ, ::Colon, j::Int)
Expand Down
6 changes: 6 additions & 0 deletions stdlib/LinearAlgebra/test/qr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,12 @@ end
@test Q2[:, :] M[:, :]
@test Q2[:, :, :] M[:, :, :]
end
# Check that getindex works if copy returns itself (#44729)
struct MyIdentity{T} <: LinearAlgebra.AbstractQ{T} end
Base.size(::MyIdentity, dim::Integer) = dim in (1,2) ? 2 : 1
Base.copy(J::MyIdentity) = J
LinearAlgebra.lmul!(::MyIdentity{T}, M::Array{T}) where {T} = M
@test MyIdentity{Float64}()[1,:] == [1.0, 0.0]
end

end # module TestQR

0 comments on commit ea82910

Please sign in to comment.