Skip to content

Commit ea82910

Browse files
authored
Avoid copy in getindex(::AbstractQ, ...) (#44729)
1 parent 68e2969 commit ea82910

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

stdlib/LinearAlgebra/src/qr.jl

+3-2
Original file line numberDiff line numberDiff line change
@@ -582,8 +582,9 @@ size(F::Union{QR,QRCompactWY,QRPivoted}) = size(getfield(F, :factors))
582582
size(Q::AbstractQ, dim::Integer) = size(getfield(Q, :factors), dim == 2 ? 1 : dim)
583583
size(Q::AbstractQ) = size(Q, 1), size(Q, 2)
584584

585-
copy(Q::AbstractQ{T}) where {T} = lmul!(Q, Matrix{T}(I, size(Q)))
586-
getindex(Q::AbstractQ, inds...) = copy(Q)[inds...]
585+
copymutable(Q::AbstractQ{T}) where {T} = lmul!(Q, Matrix{T}(I, size(Q)))
586+
copy(Q::AbstractQ) = copymutable(Q)
587+
getindex(Q::AbstractQ, inds...) = copymutable(Q)[inds...]
587588
getindex(Q::AbstractQ, ::Colon, ::Colon) = copy(Q)
588589

589590
function getindex(Q::AbstractQ, ::Colon, j::Int)

stdlib/LinearAlgebra/test/qr.jl

+6
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,12 @@ end
449449
@test Q2[:, :] M[:, :]
450450
@test Q2[:, :, :] M[:, :, :]
451451
end
452+
# Check that getindex works if copy returns itself (#44729)
453+
struct MyIdentity{T} <: LinearAlgebra.AbstractQ{T} end
454+
Base.size(::MyIdentity, dim::Integer) = dim in (1,2) ? 2 : 1
455+
Base.copy(J::MyIdentity) = J
456+
LinearAlgebra.lmul!(::MyIdentity{T}, M::Array{T}) where {T} = M
457+
@test MyIdentity{Float64}()[1,:] == [1.0, 0.0]
452458
end
453459

454460
end # module TestQR

0 commit comments

Comments
 (0)