Introduction to Broadcasting

Julia has a feature called broadcasting which makes it easy to apply a function to one or more arrays with a concise dot syntax: f.(a, b) means "apply f elementwise to a and b".

Here's a quick visualization of the way a 2-dimensional broadcast operation works on a column vector a and row vector b.

a = [2, 3, 4, 5]
b = [6 7 8 9]
12342345array a
1123412346789array b
We want to add together arrays a and b using broadcast. For infix functions the broadcasting dot goes in front of the function: a .+ b
12341234axes of a1112341234axes of b
Broadcast looks at the axes—the index ranges—of its inputs a and b to determine the axes of the output.
1234123412341234output axes
The output axes are chosen to be the longest input axes in each dimension. Here the first axis is taken from a and the second from b.
12341234123412342345234523452345extruded array a
12341234123412346666777788889999extruded array b
Once the output axes are determined, the inputs a and b are extruded to the output size by repeating elements along singleton dimensions.
12341234123412342+63+64+65+62+73+74+75+72+83+84+85+82+93+94+95+9output array
Next, the + function is broadcast across the elements of each extruded array. The arrays are the same size, so things line up neatly.
123412341234123489101191011121011121311121314output array
And now we know our a .+ b.

Another useful example of broadcasting across different shapes involves numbers, which are one-element iterables of their own value. This means you can broadcast over them:

a .^ 2
1234491625array

You can also broadcast across two arrays of the same shape. In this case the shape of the output is the same as the inputs:

a .* a
1234491625array

Julia fuses adjacent broadcast calls together, avoiding the need to allocate temporary arrays even for complicated expressions:

floor.(Int, sqrt.(a) .+ sqrt.(b))
123412343444444444454455array

For cases like the above, where you want to add a dot to every function call, you can use the macro @. to add the dots automatically:

@. floor(Int, sqrt(a) + sqrt(b))
123412343444444444454455array

This is a draft. If you have feedback, email me.

Thanks for reading!

Yuri

now()2018-09-18T23:42:35.782