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
-
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 5In this example, the values
10and20are set at the indices2and4respectively in the arrayarr. -
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 9It updates the elements at the specified indices
(1, 3)and(2, 2)in the matrixmatrixwith the values10and20respectively. - 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 6This example demonstrates setting the values
10and20at the Cartesian indices(1, 1)and(2, 2)respectively in the multidimensional arrayarr.
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.