Juliaism for vector within vector for arithmetic operations?

I would like to create one array, unnested, calculated from various arithmetic vector operations. this is easier to illustrate than to describe.

julia> 10 + [ -1, +1]*2  ## ok
2-element Array{Int64,1}:
  8
 12

julia> [ 10 + [-1,+1]*2, 20 + [-3,+5]^1 ]   ## of course, not
2-element Array{Array{Int64,1},1}:
 [8, 12]
 [17, 25]

julia> [ 10 + [i:-i]*2 for i=1:5 ]  ## or this
5-element Array{Array{Int64,1},1}:
 [12, 8]
 [14, 6]
 [16, 4]
 [18, 2]
 [20, 0]

I could use vcat without comprehensions. I could also use collect(Base.Iterators.flatten(...)).

both are ok, but maybe I am just missing a simple Julia-ism here. am I?

What result do you want? A matrix?

We need recursive broadcasting. This has struck me many times in DiffEq development.

3 Likes

single vector.

Maybe, but it doesn’t sound like this is what @iwelch is asking for — it sounds like he wants a “flattened broadcast”.

If you have a small number of broadcasts that are explicitly enumerated, of course, you can do ; or call vcat

julia> @. [ 10 + [-1,+1]*2; 20 + [-3,+5]^1 ]
4-element Array{Int64,1}:
  8
 12
 17
 25

For comprehensions, you could use splatting, e.g.

vcat(@. (10 + (-i:i)*2 for i=1:5)...)

or you could collect the flatten iterator.

1 Like

very nice. thank you steven. yes, it is not perfect, but it probably fits the bill in 9 out of 10 times.