(Not) concatenating arrays

I have a large Vector{Float64} called x, a few elements of which remain unchanged within a loop. I would like the remaining elements to reflect the values in another array b, before passing on to a function within the loop which does some heavy lifting. Something like this

    # x is preallocated outside the loop, 
    # changeidx remains the same every iteration
    # b changes on every iteration but is preallocated outside the loop 
    x[changeidx] .= b
    foo!(output, x)
    # output is also preallocated

Is there a way to send foo! the variable x without actually copying the values of b into x? Will a view help me here? Or is there a best practice for this kind of operation?

Thanks

You could use a view of x in combination with Iterators.Flatten if you only need to iterate through rather than index into the array.

That sounds like a good idea but I’m not sure I know enough about Iterators.Flatten to implement what you’re saying. Could you elaborate how I could send x with a mixture of view and flatten to foo! ?

for value in Iterators.flatten((@view(x[unchangedidx]), b))
    # do something with value
end

In 1.4 and below, it’s probably worthwhile to do xview = @view x[unchagedidx] outside of your loop since it allocates, but @view no longer allocates in 1.5, so it won’t be necessary to do so for efficiency in the future.

2 Likes