Error when adding vectors

Hello, I am new here and I would like to know why I can’t add these vectors:

mutable struct Mystruct
    a::Int
    b::SVector{3, Int64}
    c::Int 
end

v1=[Mystruct(1,(-2,-2,2),1)]
v2=[Mystruct(2,(2,2,2),1)]

v3 = v1 + v2

ERROR: MethodError: no method matching +(::Mystruct, ::Mystruct)

By “add” you mean, join v1 and v2?

Either [v1; v2] or vcat(v1, v2) does that. This will return a fresh vector. If you want to add the elements of v2 to the existing v1, use append!(v1, v2).

julia> [v1; v2]
2-element Vector{Mystruct}:
 Mystruct(1, [-2, -2, 2], 1)
 Mystruct(2, [2, 2, 2], 1)
1 Like

If you actually want to add instances of your type, you will have to tell Julia how addition is supposed to work for them. Something like:

julia> v1=[Mystruct(1,[1,2],1)]
1-element Vector{Mystruct}:
 Mystruct(1, [1, 2], 1)

julia> v2=[Mystruct(1,[3,4],1)]
1-element Vector{Mystruct}:
 Mystruct(1, [3, 4], 1)

julia> +(x::Mystruct, y::Mystruct) = Mystruct(x.a + y.a, x.b .+ y.b, x.c + y.c)
+ (generic function with 209 methods)

julia> v1+v2
1-element Vector{Mystruct}:
 Mystruct(2, [4, 6], 2)

(note here I’ve simplified things by replacing the SVector with a plain Vector in the struct definition)

1 Like

Don’t we need first to import Base.+ , before adding the new methods?

3 Likes

With

mutable struct Mystruct
    a::Int
    b::Vector{ Int64}
    c::Int 
end

v1=[Mystruct(1,[1,2],1)]
v2=[Mystruct(1,[3,4],1)]

+(x::Mystruct, y::Mystruct) = Mystruct(x.a + y.a, x.b .+ y.b, x.c + y.c)
import Base: +
v1 + v2

ERROR: MethodError: no method matching +(::Vector{Mystruct}, ::Vector{Mystruct}) You may have intended to import Base.:+

The import needs to come before the definition of the function for this to work.

(Test it in fresh REPL.)

using StaticArrays
mutable struct Mystruct
    a::Int
    b::SVector{3, Int64}
    c::Int 
end

v1=[Mystruct(1,(-2,-2,2),1)]
v2=[Mystruct(2,(2,2,2),1)]
import Base: +
+(x::Mystruct, y::Mystruct) = Mystruct(x.a + y.a, x.b .+ y.b, x.c + y.c)
v3 = v1 + v2

Done, thanks!

2 Likes

Sorry I had actually done this but forgot to copy that line!

Why the braces here? This is creating a one-element vector of your structures. Is that what you want?

2 Likes