Writing a new type for a specific kind of array (constructor error)

Welcome @gpownall !

Here you go:

struct ProbMatrix{T<:Real} <: AbstractArray{T,2}
        data
        function ProbMatrix(data::Array{T,2}) where T<:Real
                if ndims(data) != 2
                        error("Probability matrix needs to be two-dimensional")
                end
                if size(data,1) != size(data,2)
                        error("Probability matrix needs to be square.")
                end
                for col_num in 1:size(data,1)
                        if sum(data[:,col_num]) != 1
                                error("Each column of a probability matrix must sum to one.")
                        end
                end
                new{T}(data)
        end
end

Base.size(m::ProbMatrix{T}) where T = size(m.data)

Mat = [0.8 0.05 ; 0.2 0.95]

println(inv(Mat))

A = ProbMatrix(Mat);

As your struct is subtyped AbstractArray{T,2} , size needs to be defined for the new type.

There is more, you have to define, e.g. getindex . You get the error if you omit the ; in the last line:

julia> A = ProbMatrix(Mat)
2×2 ProbMatrix{Float64}:
Error showing value of type ProbMatrix{Float64}:
ERROR: getindex not defined for ProbMatrix{Float64}

We had another similar thread, where you can find a few details about what was wrong in general: Inner constructor – checking for equal lengths

1 Like