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

  1. 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
    9

    In this example, the + operation is broadcast between arrays A and B, and the result is stored in array C using broadcast!.

  2. 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
    729

    In this example, the pow function is broadcast between arrays A and B, and the result is stored in array C using broadcast!.

  3. 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
    18

    This example shows how to update array A in-place with the result of broadcasting the * operation between arrays A and B.

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.

*Required Field
Details

Checking you are not a robot: