用struct构造自己的对角矩阵报错,怎么处理呢?

struct My_Diagonal{T, AT <: AbstractVector{T}} <: AbstractArray{T,2}

buffer :: AT

end

My_Diagonal(buffer::AbstractVector) = My_Diagonal{eltype(buffer), typeof(buffer)}(buffer)

buffer = [1,2,3,4,5]

x = My_Diagonal(buffer)

报错,这种问题怎么解决呢?求指点。
ERROR: MethodError: no method matching size(::My_Diagonal{Int64, Vector{Int64}})
Closest candidates are:
size(::AbstractArray{T, N}, ::Any) where {T, N} at C:\Users\Administrator\AppData\Local\Programs\Julia-1.7.1\share\julia\base\abstractarray.jl:42
size(::Union{LinearAlgebra.Adjoint{T, var"#s859"}, LinearAlgebra.Transpose{T, var"#s859"}} where {T, var"#s859"<:(AbstractVector)}) at C:\Users\Administrator\AppData\Local\Programs\Julia-1.7.1\share\julia\stdlib\v1.7\LinearAlgebra\src\adjtrans.jl:172
size(::Union{LinearAlgebra.Adjoint{T, var"#s859"}, LinearAlgebra.Transpose{T, var"#s859"}} where {T, var"#s859"<:(AbstractMatrix)}) at C:\Users\Administrator\AppData\Local\Programs\Julia-1.7.1\share\julia\stdlib\v1.7\LinearAlgebra\src\adjtrans.jl:173

经测试,这是无法显示的问题。(Error showing value of type My_Diagonal{Int64, Vector{Int64}}:
自定义显示方式或定义 size 函数从而 enable 默认显示函数 或不进行显示

1 个赞

我在repl环境下,运行size函数,发现size函数找不到了。不知道这是咋回事,Base库不是自动就有的吗?
julia> size([1,2,3])
ERROR: MethodError: no method matching size(::Vector{Int64})
You may have intended to import Base.size
之后我重启了julia,发现size函数可以使用了。 :rofl:
struct My_Diagonal{T, AT <: AbstractVector{T}} <: AbstractArray{T,2}

buffer :: AT

end

My_Diagonal(buffer::AbstractVector) = My_Diagonal{eltype(buffer), typeof(buffer)}(buffer)

buffer = [1,2,3,4,5]

Base.size(x::My_Diagonal) = (size(x.buffer, 1), size(x.buffer, 1))

Base.getindex(x::My_Diagonal,i,j) = i == j ? x.buffer[i] : zero(eltype(x))

x = My_Diagonal(buffer)

显示为:
5×5 My_Diagonal{Int64, Vector{Int64}}:
1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5

确实是无法显示的问题。