From e2ea152b4ba503a9f8b8d6d3f33f23f82a94a996 Mon Sep 17 00:00:00 2001 From: Simon Byrne Date: Tue, 29 Mar 2022 00:35:02 -0700 Subject: [PATCH] Allow pushing to vector after 3-arg ldiv! (#43510) Co-authored-by: Daniel Karrasch --- stdlib/LinearAlgebra/src/factorization.jl | 17 ++++++++++++++--- stdlib/LinearAlgebra/test/lu.jl | 9 +++++++++ stdlib/LinearAlgebra/test/qr.jl | 8 ++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/stdlib/LinearAlgebra/src/factorization.jl b/stdlib/LinearAlgebra/src/factorization.jl index 626a1ae7b1a74..bfaffd0dccd14 100644 --- a/stdlib/LinearAlgebra/src/factorization.jl +++ b/stdlib/LinearAlgebra/src/factorization.jl @@ -114,8 +114,18 @@ end /(B::TransposeAbsVec, adjF::Adjoint{<:Any,<:Factorization}) = adjoint(adjF.parent \ adjoint(B)) -# support the same 3-arg idiom as in our other in-place A_*_B functions: -function ldiv!(Y::AbstractVecOrMat, A::Factorization, B::AbstractVecOrMat) +function ldiv!(Y::AbstractVector, A::Factorization, B::AbstractVector) + require_one_based_indexing(Y, B) + m, n = size(A, 1), size(A, 2) + if m > n + Bc = copy(B) + ldiv!(A, Bc) + return copyto!(Y, 1, Bc, 1, n) + else + return ldiv!(A, copyto!(Y, B)) + end +end +function ldiv!(Y::AbstractMatrix, A::Factorization, B::AbstractMatrix) require_one_based_indexing(Y, B) m, n = size(A, 1), size(A, 2) if m > n @@ -123,7 +133,8 @@ function ldiv!(Y::AbstractVecOrMat, A::Factorization, B::AbstractVecOrMat) ldiv!(A, Bc) return copyto!(Y, view(Bc, 1:n, :)) else - return ldiv!(A, copyto!(Y, view(B, 1:m, :))) + copyto!(view(Y, 1:m, :), view(B, 1:m, :)) + return ldiv!(A, Y) end end diff --git a/stdlib/LinearAlgebra/test/lu.jl b/stdlib/LinearAlgebra/test/lu.jl index f07ceceec8444..e86cd583c0904 100644 --- a/stdlib/LinearAlgebra/test/lu.jl +++ b/stdlib/LinearAlgebra/test/lu.jl @@ -426,4 +426,13 @@ end end end +@testset "can push to vector after 3-arg ldiv! (#43507)" begin + u = rand(3) + A = rand(3,3) + b = rand(3) + ldiv!(u,lu(A),b) + push!(b,4.0) + @test length(b) == 4 +end + end # module TestLU diff --git a/stdlib/LinearAlgebra/test/qr.jl b/stdlib/LinearAlgebra/test/qr.jl index a7b24f08385f2..d5f5537b2f63f 100644 --- a/stdlib/LinearAlgebra/test/qr.jl +++ b/stdlib/LinearAlgebra/test/qr.jl @@ -270,11 +270,19 @@ end b = randn(3) b0 = copy(b) c = randn(2) + B = randn(3,3) + B0 = copy(B) + C = randn(2,3) @test A \b ≈ ldiv!(c, qr(A ), b) @test b == b0 + @test A \B ≈ ldiv!(C, qr(A ), B) + @test B == B0 c0 = copy(c) + C0 = copy(C) @test Ac\c ≈ ldiv!(b, qr(Ac, ColumnNorm()), c) @test c0 == c + @test Ac\C ≈ ldiv!(B, qr(Ac, ColumnNorm()), C) + @test C0 == C end @testset "Issue reflector of zero-length vector" begin