This is a follow-up question from How to solve set of nonlinear fixed-point equations using Anderson acceleration in NLsolve.jl?. Suppose I have a VectorOfArray object
z = VectorOfArray([rand(4), rand(4)])
Then the following operations are not allowed
t .- rand(8) # ERROR: DimensionMismatch("arrays could not be broadcast to a common size; got a dimension with lengths 4 and 8")
t - rand(8) # ERROR: DimensionMismatch("dimensions must match: a has dims (Base.OneTo(32), Base.OneTo(2)), b has dims (Base.OneTo(64),), mismatch at 1")
In practice, it will be more complicated where the elements inside the VectorOfArray shall be any AbstractArray.
It is sensible to do following using copyto!
function Base.copyto!(vf::AbstractOfArray{T}, v::AbstractVector) where {T<:MyAbstractArrayType}
total_elements = 0
for i in 1:length(vf)
total_elements += length(vf[1])
end
total_elements == length(v) || error("Length mismatch.")
j = 1
for i in 1:length(vf)
n = length(vf[i])
vf[i] .= v[j:j+n-1]
j += n
end
end
z1 = VectorOfArray([rand(4), rand(4)])
z2 = VectorOfArray([rand(4), rand(4)])
copyto!(z1, rand(8))
# Use RecursiveArrayTools broadcasting
z2 .- z1
# Or
z2 - z1
Or shall I define a new operator method as
function Base.-(vf::AbstractOfArray{T}, v::AbstractVector) where {T<:MyAbstractArrayType}
total_elements = 0
for i in 1:length(vf)
total_elements += length(vf[1])
end
total_elements == length(v) || error("Length mismatch.")
out = deepcopy(vf)
j = 1
for i in 1:length(vf)
n = length(vf[i])
out[i] = vf[i] - v[j:j+n-1]
j += n
end
return out
end
However, this approach again relies on whether we can do -
with vf[
i]and
v` which may fail.
I want to know the best practice to solve this kind of issue. Thanks!