Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid copy in getindex(::AbstractQ, ...) #44729

Merged
merged 2 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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