Broadcasting in Julia's ecosystem consists of mapping a function across an infinite number of arguments. It allows performing binary operations, element-by-element, on arrays of different sizes, such as adding a vector to each column of a matrix.
The powerful broadcast()
function allows us to combine arrays and scalars or arrays of different shapes/dimensions, without using any extra memory.
The syntax of the broadcast()
function is:
broadcast(f, args...)
where f
represents the function to apply.
Starting from Julia version 0.5, the dot call syntax f.(args...)
is equivalent to the above. Similarly, the dot macro syntax @. f(args)
assures similar functionality and it is quite handy when working with long expressions that involve several operations to be broadcasted together.
Let us go through the following examples to understand the underlying concept:
This example shows how to apply the broadcast
function to add two arrays of different dimensions:
a = [1,2,3]b = [1 2;3 4;5 6]output = broadcast(+,a,b)print(output)
Let's explain the code widget above:
Line 1: Defines a 1D array and store it in variable a
.
Line 2: Defines a 2D array and store it in variable b
.
Line 3: Invokes the broadcast
function in order to add the first array to the second one while using the addition operator +
in the broadcast function.
Line 4: Displays the resulting output.
This example shows how to concatenate each integer value within an array to a string parameter using the broadcast
function. This example exhibits also the dot call syntax and the dot macro syntax of this function.
function concat(s,n)output = "\n $s=$n"print(output)enda = [1,2,3,4,5]print("\n broadcast(concat,'Counter',a):")broadcast(concat,"Counter",a)print("\n\n concat.('Counter',a):")concat.("Counter",a)print("\n\n @. concat('Counter',a):")@. concat("Counter",a)
Let's go through the code presented above:
Lines 1–4: Defines a function concat
that accepts two parameters, concatenates them, and prints the result on a new line.
Line 5: Defines an array of integer values.
Line 6: Displays a message showing the syntax of the broadcast
function to be executed.
Line 7: Invokes the broadcast
function in order to concatenate each integer value within the array a
to the specified string parameter Counter
while applying the function concat
.
Line 9: Displays a message showing the dot call syntax of the broadcast
function to be executed.
Line 10: Invokes the dot call syntax of the broadcast
function in order to concatenate each integer value within the array a
to the specified string parameter Counter
while applying the function concat
.
Line 12: Displays a message showing the dot macro syntax of the broadcast
function to be executed.
Line 13: Invokes the dot macro syntax of the broadcast
function in order to concatenate each integer value within the array a
to the specified string parameter Counter
while applying the function concat
.
Free Resources