Type of array views

Hi,

I have just discovered the catch with passing array slices to a function that is to modify the array entries. “view” is the solution. (9792).

The rub is, that while c[:,i] is a plain ol’ vector, view(c,:,i) has some complicated type. Logical enough, but throws a spanner in the works of my dispatch system.

function init!(a)
    for i = 1:2
        a[i] = 1. *i
    end
end
function initstrict!(a::Vector{Float64})
    for i = 1:2
        a[i] = 1. *i
    end
end

a = Array{Float64,1}(undef,2)
init!(a)   # a is initialized
b = Array{Float64,1}(undef,2)
init!(b[:]) # deepcopy of b passed, b not initialised
c = Array{Float64,2}(undef,2,3)
init!(view(c,:,1)) # view to the rescue, 1st column initialised
c = Array{Float64,2}(undef,2,3) 
initstrict!(view(c,:,1))  # uh oh, type mismatch!

I can workaround the issue with

c = Array{Float64,2}(undef,2,3) 
a = Array{Float64,1}(undef,2)
initstrict!(a)
c[:,1] = a

but that’s a deepcopy and more code. I do not consider it an option to rewrite initstrict! to accept (“vectors or any vector-like view”).

There are other workarounds in my specific case, but I am here to learn: passing an array slice, easy method dispatching and no deepcopy? Yeah, can I have my slice and eat it?

Why not? Is it important that the function accepts only Vector{Float64} and not AbstractVector{Float64}?

1 Like

Great, if its as simple as “AbstractVector”, that’s great. I was afraid of some ugly Union of whatnot where…

Is the literal range 1:2 important?

If you just want to initialize the values with the corresponding indices, then a .= eachindex(a) or a .= 1:length(a) would be more appropriate.

And there is no need using C idioms like 1. * i when assigning Ints into a Float array, the rhp is automatically converted to the array element type (using convert). For an explicit conversion, a[i] = convert(Float64, i) or a[i] = Float64(i) would be preferred.

1 Like

Hi Vasily,
No, no the literal range was just laziness in writing up my question - in real code I would indeed have used eachindex (lazy in the sense that the reflexes are not quite rubbed in yet!).

Point taken on conversions.

Thank you!

1 Like