broadcast!_function
broadcast!_function(f)
Like broadcast_function
, but for broadcast!
.
Examples
In the Julia programming language, the function broadcast!(f, args...)
Modify the given args
in-place by applying the function f
to each corresponding element of the arguments.
jldoctest
julia> arr = [1, 2, 3, 4, 5];
julia> broadcast!((x) -> x^2, arr)
5-element Array{Int64,1}:
1
4
9
16
25
Provide common examples of its use. If there are any common mistakes users make, add an example.
-
Square each element in an array:
julia> arr = [1, 2, 3, 4, 5]; julia> broadcast!((x) -> x^2, arr) 5-element Array{Int64,1}: 1 4 9 16 25
This example applies the
square
function to each element of the arrayarr
in-place. -
Element-wise addition of two arrays:
julia> arr1 = [1, 2, 3, 4, 5]; julia> arr2 = [10, 20, 30, 40, 50]; julia> broadcast!(+, arr1, arr2) 5-element Array{Int64,1}: 11 22 33 44 55
It performs element-wise addition between
arr1
andarr2
in-place. - Increment each element by a constant:
julia> arr = [1, 2, 3, 4, 5]; julia> broadcast!((x) -> x + 10, arr) 5-element Array{Int64,1}: 11 12 13 14 15
This example increments each element of the array
arr
by 10 in-place.
Common mistake example:
julia> arr1 = [1, 2, 3];
julia> arr2 = [10, 20, 30, 40];
julia> broadcast!(+, arr1, arr2)
ERROR: DimensionMismatch: arrays could not be broadcast to a common size
In this example, the arrays arr1
and arr2
have different sizes. It's important to ensure that the dimensions of the arrays being operated on are compatible to avoid such errors when using broadcast!
.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.