setElems function
array float[]string[]bool[] Array for which elements are set.
indices, rowIndices, colIndices floatfloat[]bool[] Zero-based index values, arrays of indices, or arrays of logical values.
values floatstringboolfloat[]string[]bool[] Value or array of values to be set.
Returns an array containing the new element values.
The setElems function sets elements of an array to new values. Elements are selected by index values, index arrays, or logical arrays. Indexing follows the same rules as the index operator.
1D indexing
One element at a specific zero-based index position can be replaced by a new value. Several elements can be set at once using an index array.
array1d = [0,0,0,0,0,0] setElems(array1d, 2, 1) [0,0,1,0,0,0] setElems(array1d, [1:4], 1) [0,1,1,1,1,0]
Elements selected by an index array can also be replaced by a value array. Both arrays must have the same size. Repeated indices override earlier values.
setElems(array1d, [1,3,5], [1:3]) [0,1,0,2,0,3] setElems(array1d, [5,1,3], [1:3]) [0,2,0,3,0,1] setElems(array1d, [1,1,1], [1:3]) [0,3,0,0,0,0]
2D indexing
2D arrays can be indexed by row indices and column indices.
array2d = [0,0,0;
0,0,0;
0,0,0]
setElems(array2d, 1, 1, 5) [0,0,0; 0,5,0; 0,0,0]
setElems(array2d, [0,2], [0:2], 1) [1,1,1; 0,0,0; 1,1,1]
A values array can be set as well. It must have the same dimensions as prescribed by the row and column index arrays. Repeated indices override earlier values.
setElems(array2d, [1,2], [0,2], [1,2;3,4]) [0,0,0; 1,0,2; 3,0,4] setElems(array2d, [2,1], [2,0], [1,2;3,4]) [0,0,0; 4,0,3; 2,0,1] setElems(array2d, [1,1], [0,2], [1,2;3,4]) [0,0,0; 3,0,4; 0,0,0]
Logical indexing
Logical indexing can be used to select values.
sequence = [1:7] setElems(sequence, sequence .> 4, 4) [1,2,3,4,4,4,4] setElems(sequence, sequence .> 4, [3,2,1]) [1,2,3,4,3,2,1]
Value arrays must have the same size, or the same dimensions for 2D indexing, as the number of selected elements.
Indexing out of bounds
Negative indices are ignored, which means the respective values are not set. Indices greater than or equal to the number of elements, rows, or columns enlarge the array. Missing elements are filled with default values.
array = [1,1] setElems(array, 3, 5) [1,1,0,5] setElems(array, 2, 2, 5) [1,1,0; 0,0,0; 0,0,5]
Related
Examples
Enumerate value
enumerate(array, value) with( found := array .== value ) = setElems(floatArray, found, [1:sum(found)]) f = enumerate(["a","c","b","a","d","a"], "a") // [1,0,0,2,0,3]
Create diagonal matrix
diag(n) = setElems(floatArray[1:n,1:n], [0:n+1:n*n-1], 1)
f = diag(3) // [1,0,0;
// 0,1,0;
// 0,0,1]
Reshape array
reshape(array, rows, cols)
= setElems(floatArray[1:rows,1:cols], [0:rows*cols-1], array)
array = [1,2,3;
4,5,6]
f = reshape(array, 3, 2) // [1,2;
// 3,4;
// 5,6]