Extension of ^-operator for Vector{Vector{Real}}

Hi,

I would like to extend the ^-operator for Vector{Vector{Real}}. I tried the following implementation, but I get an error message :MethodError: no method matching ^(::Vector{Vector{Int16}}, ::Int64).

import Base:^
Base.:^(vec::Vector{Vector{Real}}, exponent::Real) = for i in 1:length(vec); vec[i] = vec[i].^convert(eltype(eltype(vec)), exponent); end

So it seems that method definition isn’t correct. Does somebody know what is wrong? If use the concrete data types e.g. Vector{Vector{Int16}} and Int64 it works.

This implementation works

import Base:^
function Base.:^(vec::Vector{Vector{T}}, exponent::S) where {T<:Real, S<:Real}
    vec_tmp = deepcopy(vec)
    for i in 1:length(vec_tmp)
        vec_tmp[i] = vec_tmp[i].^convert(eltype(eltype(vec_tmp)), exponent)
    end
    return vec_tmp
end
[v.^exponent for v in vec] 

?
What you’re doing is type piracy, btw, so not a good idea…

5 Likes

Ok, thanks for the hint

You can just slightly modify this and your original definition should work: replace the above with ::Vector{<:Vector{<:Real}}.

2 Likes