broadcast
broadcast(f, As...)
Broadcasts the arrays As
to a common size by expanding singleton dimensions, and returns an array of the results f(as...)
for each position.
Examples

Broadcast a function over arrays:
julia> arr1 = [1, 2, 3]; julia> arr2 = [4, 5, 6]; julia> broadcast(+, arr1, arr2) 3element Array{Int64,1}: 5 7 9
This example broadcasts the addition function
+
overarr1
andarr2
, resulting in a new array where each element is the sum of the corresponding elements fromarr1
andarr2
. 
Broadcast a function over a scalar and an array:
julia> scalar = 10; julia> arr = [1, 2, 3]; julia> broadcast(*, scalar, arr) 3element Array{Int64,1}: 10 20 30
Here, the multiplication function
*
is applied elementwise between the scalar valuescalar
and each element of the arrayarr
.  Broadcast a function over multiple arrays:
julia> arr1 = [1, 2, 3]; julia> arr2 = [4, 5, 6]; julia> arr3 = [7, 8, 9]; julia> broadcast(, arr1, arr2, arr3) 3element Array{Int64,1}: 10 11 12
This example broadcasts the subtraction function

overarr1
,arr2
, andarr3
, resulting in a new array where each element is the difference of the corresponding elements from the three arrays.
Common mistake example:
julia> arr1 = [1, 2, 3];
julia> arr2 = [4, 5];
julia> broadcast(+, arr1, arr2)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
In this example, the arrays arr1
and arr2
are not compatible for broadcasting because their sizes do not match. It's important to ensure that the arrays being broadcasted have compatible dimensions to avoid such errors.
See Also
Array, broadcast, cat, combinations, conj!, digits!, fieldnames, fill, fill!, last, length, maximum, minimum, ones, parent, parentindexes, partitions, permutations, pointer, pointer_to_array, promote_shape, rand!, reshape, scale, similar, sum, sum_kbn, takebuf_array, transpose!, vec, zeros,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.