Array of Arrays + Array of Scalar

The following code used to work on ver.0.6.4, issues a warning on ver.0.7, and outputs an error on ver.1.0.4 as shown. What will be the right way to do in ver.1?

a = [[1 2; 3 4], [5 6; 7 8]]
2-element Array{Array{Int64,2},1}:
 [1 2; 3 4]
 [5 6; 7 8]
b = [1, 2]
2-element Array{Int64,1}:
 1
 2
a .+ b
MethodError: no method matching +(::Array{Int64,2}, ::Int64)
Closest candidates are:
  +(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:502
  +(!Matched::Complex{Bool}, ::Real) at complex.jl:292
  +(!Matched::Missing, ::Number) at missing.jl:93
  ...



Stacktrace:

 [1] _broadcast_getindex_evalf at .\broadcast.jl:582 [inlined]

 [2] _broadcast_getindex at .\broadcast.jl:555 [inlined]

 [3] getindex at .\broadcast.jl:515 [inlined]

 [4] copy at .\broadcast.jl:790 [inlined]

 [5] materialize(::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1},Nothing,typeof(+),Tuple{Array{Array{Int64,2},1},Array{Int64,1}}}) at .\broadcast.jl:756

 [6] top-level scope at In[3]:1

You can use an array comprehension: [a[i] .+ b[i] for i in 1:length(b)]

Or, for example: ((x,y) -> x .+ y).(a,b).

Note that my previous answer wasn’t equivalent to a .+ b in pre Julia 1.0.

1 Like

Thank you :smile: Both of them worked.

You’re welcome. Glad I could be of help.

1 Like