How to use dot notation when extending functions for a user-defined type?

Let’s say that I create a new struct called MyMatrix:

import Base: size, getindex

struct MyMatrix{T} <: AbstractMatrix{T}
    X::Matrix{T}

    function MyMatrix(n::Int)
        new{Float64}(rand(n,n)) # For sake of the example
    end
end

Base.size(X::MyMatrix) = size(X.X)
Base.getindex(X::MyMatrix, inds...) = getindex(X.X, inds...)

Now, if I use - from Base, the type MyMatrix is not preserved (which is expected):

julia> X = MyMatrix(2)
2×2 MyMatrix{Float64}:
 0.984525  0.843545
 0.862174  0.266042

julia> X .- 1
2×2 Array{Float64,2}:
 -0.0154746  -0.156455
 -0.137826   -0.733958

The question is: how can I extend - so that it uses . notation and preserves MyMatrix type? Ideally, I’d want:

julia> X .- 1
2×2 MyMatrix{Float64,2}:
 -0.0154746  -0.156455
 -0.137826   -0.733958

Thanks!

if you want your custom type to be broadcastable, you need to implement the broadcast interface:
https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting-1

2 Likes

Thanks!