# 用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

1 个赞

julia> size([1,2,3])
ERROR: MethodError: no method matching size(::Vector{Int64})
You may have intended to import Base.size

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