How to predict the type of a view(A, ...)

I often want to pre-allocate a container for a bunch of views, but have no idea how to predict the type that view will return, and therefore don’t know how to make a container for them. I understand that this may be difficult to do in an extremely general way, but often my views end up being the same type anyways (e.g. a bunch of slices from the same array).

Any pointers?

I typically just do typeof on an example. This is not a good generalizeable solution but is very cheap to implement even if you don’t understand anything about the view method or SubArray type (which I don’t).

2 Likes

Yeah that’s what I do too, but I wish there was some better way…

Effectively the same, but how about:

julia> allocate(x::T, n) where {T} = Vector{T}(undef, n)
allocate (generic function with 1 method)

julia> allocate(3, 10)
10-element Array{Int64,1}:
 4570098240
 4570098160
          1
 4570098320
 4570098400
 4570098480
          3
          7
          2
          1

julia> allocate("hello", 10)
10-element Array{String,1}:
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef

julia> M = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> v = view(M, 1:2, 1:1)
2×1 view(::Array{Int64,2}, 1:2, 1:1) with eltype Int64:
 1
 3

julia> allocate(v, 10)
10-element Array{SubArray{Int64,2,Array{Int64,2},Tuple{UnitRange{Int64},UnitRange{Int64}},false},1}:
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
1 Like

Clever solution! I may start using something similar to that. I think the “pain” (which is really not that bad) to either your allocate or doing what @Juser suggested is that you have to break up for loops. You have to run the first element, pre-allocate, put the first element into the array, then run the rest. It’s fine for one offs but I find myself turning to map quite often to avoid having to do all of that.

Sounds like it could be a case for broadcasting (.).

Is there a benefit to broadcasting when you don’t need to expand a dimension? I assumed that broadcasting and map would have similar performance.