broadcast_setindex!

broadcast_setindex!(A, X, inds...)

Broadcasts the X and inds arrays to a common size and stores the value from each position in X at the indices given by the same positions in inds.

Examples

  1. Modify specific elements of an array using indices:

    julia> arr = [1, 2, 3, 4, 5];
    julia> indices = [2, 4];
    julia> values = [10, 20];
    julia> broadcast_setindex!(arr, values, indices...)
    5-element Array{Int64,1}:
    1
    10
    3
    20
    5

    In this example, the values 10 and 20 are set at the indices 2 and 4 respectively in the array arr.

  2. Update specific elements of a matrix using indices:

    julia> matrix = [1 2 3; 4 5 6; 7 8 9];
    julia> indices = [(1, 3), (2, 2)];
    julia> values = [10, 20];
    julia> broadcast_setindex!(matrix, values, indices...)
    3×3 Matrix{Int64}:
    1   2  10
    4  20   6
    7   8   9

    It updates the elements at the specified indices (1, 3) and (2, 2) in the matrix matrix with the values 10 and 20 respectively.

  3. Assign values to specific elements of a multidimensional array:
    julia> arr = [1 2 3; 4 5 6];
    julia> indices = [CartesianIndex(1, 1), CartesianIndex(2, 2)];
    julia> values = [10, 20];
    julia> broadcast_setindex!(arr, values, indices...)
    2×3 Matrix{Int64}:
    10   2   3
     4  20   6

    This example demonstrates setting the values 10 and 20 at the Cartesian indices (1, 1) and (2, 2) respectively in the multidimensional array arr.

Common mistake example:

julia> arr = [1, 2, 3];
julia> indices = [1, 2, 3, 4];
julia> values = [10, 20, 30, 40];
julia> broadcast_setindex!(arr, values, indices...)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")

In this example, the size of the indices array is different from the size of the values array. It's important to ensure that the arrays being broadcasted have compatible sizes to avoid a DimensionMismatch 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: