# setElems 函数

### 语法

• float[]/string[]/bool[] setElems(array, indices, values)
• float[]/string[]/bool[] setElems(array, rowIndices, colIndices, values)

### 参数

1. array -（float[]、bool[]、string[]
设置多个元素的数组。
2. indices, rowIndices, colIndices—(float, float[], bool[])
从零开始的索引值或指数数组或逻辑值数组。
3. values—(float, string, bool, float[], bool[], string[])
要设置的值或值数组。

### 描述

setElems 函数将数组的元素设置为新值。 按索引值、索引数组或逻辑数组选择元素。 索引遵循与索引运算符相同的规则（请参阅其中的详细说明）。

### 1d 索引

``````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]``````

``````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 索引

2d 数组可以通过行索引和列索引进行索引。

``````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]``````

``````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]``````

### 逻辑索引

``````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]``

### 索引超出范围

``````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]``````

### 示例

#### 枚举值

``````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]``````

#### 创建对角线矩阵

``````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, 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]``````