Let's say that I have a type defined as
struct MyVectorType{T} <: AbstractVector{T}
x::Vector{T}
end
I would like to be able to define getindex
such that when I do
A = MyVectorType([1, 1, 2, 3, 5, 8])
A[3]
I get 2
, and if I do
A[[1, 3, 5]]
A[1:3]
I'll get MyVectorType([1,2,5])
and MyVectorType([1,1,2])
, i.e. a new instance of MyVectorType
.
You mean something like this?
Base.getindex(x::MyVectorType, i::AbstractVector) = MyVectorType(x.x[i])
Base.getindex(x::MyVectorType, i) = x.x[i]
Unfortunately I've already tried something similar to this and it doesn't work. I get an error
ERROR: LoadError: MethodError: Cannot `convert` an object of type
Int64 to an object of type
MyVectorType
I can't guess what you did to get there. Can you give a complete example that reproduces it?
Last updated: Dec 28 2024 at 04:38 UTC