broadcast!
broadcast!(f, dest, As...)
Like broadcast, but store the result of broadcast(f, As...) in the dest array. Note that dest is only used to store the result, and does not supply arguments to f unless it is also listed in the As, as in broadcast!(f, A, A, B) to perform A[:] = broadcast(f, A, B).
Examples
-
Broadcasting an operation and storing the result in a destination array:
julia> A = [1, 2, 3]; julia> B = [4, 5, 6]; julia> C = similar(A); julia> broadcast!(+, C, A, B) 3-element Array{Int64,1}: 5 7 9In this example, the
+operation is broadcast between arraysAandB, and the result is stored in arrayCusingbroadcast!. -
Broadcasting a function with multiple arguments:
julia> A = [1, 2, 3]; julia> B = [4, 5, 6]; julia> C = similar(A); julia> broadcast!(pow, C, A, B) 3-element Array{Int64,1}: 1 32 729In this example, the
powfunction is broadcast between arraysAandB, and the result is stored in arrayCusingbroadcast!. - Updating an array in-place with broadcasting:
julia> A = [1, 2, 3]; julia> B = [4, 5, 6]; julia> broadcast!(*, A, A, B) 3-element Array{Int64,1}: 4 10 18This example shows how to update array
Ain-place with the result of broadcasting the*operation between arraysAandB.
Common mistake example:
julia> A = [1, 2, 3];
julia> B = [4, 5, 6, 7];
julia> C = similar(A);
julia> broadcast!(+, C, A, B)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
In this example, the arrays A and B have different sizes, causing a DimensionMismatch error. Make sure the arrays being broadcasted have compatible dimensions to avoid this error.
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.