From 1a275232ceea8cc1f8a8df43f9a003533726d0ba Mon Sep 17 00:00:00 2001 From: Sheehan Olver Date: Thu, 24 Mar 2022 10:32:38 +0000 Subject: [PATCH 1/2] Avoid copy in getindex(::AbstractQ, ...) --- stdlib/LinearAlgebra/src/qr.jl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/stdlib/LinearAlgebra/src/qr.jl b/stdlib/LinearAlgebra/src/qr.jl index 16e066ed1e030..4e1cc83b468f5 100644 --- a/stdlib/LinearAlgebra/src/qr.jl +++ b/stdlib/LinearAlgebra/src/qr.jl @@ -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) From d462e646f71a82934a0cfa34c74161de4c6ae5a9 Mon Sep 17 00:00:00 2001 From: Sheehan Olver Date: Fri, 25 Mar 2022 09:39:00 +0000 Subject: [PATCH 2/2] Add test --- stdlib/LinearAlgebra/test/qr.jl | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/stdlib/LinearAlgebra/test/qr.jl b/stdlib/LinearAlgebra/test/qr.jl index f9acbdb376465..a7b24f08385f2 100644 --- a/stdlib/LinearAlgebra/test/qr.jl +++ b/stdlib/LinearAlgebra/test/qr.jl @@ -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