问题描述
我正在通过扩展LinearAlgebra
模块中提供的功能来创建自定义矩阵库。我通过在自定义MyLinearAlgebra
模块中创建自定义结构来做到这一点,该模块直接导入默认的线性代数结构并覆盖许多常见的LA功能。我的问题特别是关于如何覆盖反斜杠功能的。这是我的"MyLinearAlgebra.jl"
:
module MyLinearAlgebra
import LinearAlgebra
import Base: getindex,setindex!,size
export
# Types
LocalMatrix,SolutionVector,# Functions
lp_error!,lp_norm,true_size
include("SolutionVector.jl")
include("LocalMatrix.jl")
end
我现在只关注LocalMatrix.jl
,
"""
struct LocalMatrix{T} <: AbstractMatrix{T}
Block diagonal structure for local matrix. `A[:,:,iS,iK]` is a block matrix for
state iS and element iK
"""
struct LocalMatrix{T} <: AbstractMatrix{T}
data::Array{T,4}
factorizations::Array{Any,2}
function LocalMatrix(data::Array{T,4}) where {T}
new{T}(data,Array{Any}(undef,size(data,3),4)))
end
end
# [... a lot of things that are already working including: ldiv!]
"""
ldiv!(A::LocalMatrix,x::SolutionVector)
In-place linear solve A\\x using block-diagonal LU factorizations. Compute this
block-diagonal factorization if not yet computed.
"""
function LinearAlgebra.ldiv!(A::LocalMatrix,x::SolutionVector)
println("my ldiv! works fine")
x
end
# [ ... and yet this does not work ]
"""
A::LocalMatrix \\ x::SolutionVector
Linear solve A\\x using block-diagonal LU factorizations. Compute this
block-diagonal factorization if not yet computed.
"""
function (\)(A::LocalMatrix,x::SolutionVector)
println("my \\ never prints out in any tests")
(m,n,ns,ne) = size(A.data)
(nx,nsx,nex) = size(x.data)
@assert n == nx && ne == nex && m == n
b = deepcopy(x)
LinearAlgebra.ldiv!(A,b)
end
在测试中,我可以完全按预期使用ldiv!
函数,但不能使用\
函数-它仅使用在其他地方编写的一些标准实现。我相信这可能是因为我的反斜杠功能不具备LinearAlgebra反斜杠功能的资格,但是我不确定。尝试将功能限定为LinearAlgebra.(\)(A::LocalMatrix,x::SolutionVector)
失败,并出现语法错误invalid function name
。还有另一种方法可以做到这一点,还是我在这里缺少有关模块的更基本的知识?
解决方法
\
是在Base中定义的,因此:
julia> "a" \ "b"
ERROR: MethodError: no method matching adjoint(::String)
julia> Base.:\(::String,::String) = "hello"
julia> "a" \ "b"
"hello"
但是,由于将其导入到LinearAlgebra
中,以下内容也对我有用(我正在使用新的会话):
julia> using LinearAlgebra
julia> "a" \ "b"
ERROR: MethodError: no method matching adjoint(::String)
julia> LinearAlgebra.:\(::String,::String) = "hello"
julia> "a" \ "b"
"hello"
Julia将为相同的函数(在Base中定义)添加一个方法。