# 数组索引

### 按元素位置进行索引

`A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]`
```A = 4×4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ```
`e = A(3,2)`
```e = 10 ```

`e``A` 中位于 3,2 位置（第三行第二列）的元素。

`r = A(2,[1 3])`
```r = 1×2 5 7 ```

`r = A(1:3,2:4)`
```r = 3×3 2 3 4 6 7 8 10 11 12 ```

`r = A(1:3,2:end)`
```r = 3×3 2 3 4 6 7 8 10 11 12 ```

`r = A(:,3)`
```r = 4×1 3 7 11 15 ```

`t = [datetime(2018,1:5,1); datetime(2019,1:5,1)]`
```t = 2x5 datetime 01-Jan-2018 01-Feb-2018 01-Mar-2018 01-Apr-2018 01-May-2018 01-Jan-2019 01-Feb-2019 01-Mar-2019 01-Apr-2019 01-May-2019 ```
`march1 = t(:,3)`
```march1 = 2x1 datetime 01-Mar-2018 01-Mar-2019 ```

```A = rand(3,3,3); e = A(2,3,1)```
```e = 0.5469 ```

### 使用单个索引进行索引

`A = [12 36 91; 45 29 48; 33 25 11]`
```A = 3×3 12 36 91 45 29 48 33 25 11 ```
`Alinear = A(:)`
```Alinear = 9×1 12 45 33 36 29 25 91 48 11 ```

`e = A(3,2)`
```e = 25 ```
`elinear = A(6)`
```elinear = 25 ```

`s = sum(A(:))`
```s = 330 ```

`sub2ind``ind2sub` 函数可用于在数组的原始索引和线性索引之间进行转换。例如，计算 `A` 的第 3,2 个元素的线性索引。

`linearidx = sub2ind(size(A),3,2)`
```linearidx = 6 ```

`[row,col] = ind2sub(size(A),6)`
```row = 3 ```
```col = 2 ```

### 使用逻辑值进行索引

`A = [1 2 6; 4 3 6]`
```A = 2×3 1 2 6 4 3 6 ```
`B = [0 3 7; 3 7 5]`
```B = 2×3 0 3 7 3 7 5 ```
`ind = A<B`
```ind = 2x3 logical array 0 1 1 0 1 0 ```

`Avals = A(ind)`
```Avals = 3×1 2 3 6 ```
`Bvals = B(ind)`
```Bvals = 3×1 3 7 7 ```

MATLAB 中的 is 函数还返回逻辑数组，指示输入中的哪些元素满足特定条件。例如，使用 `ismissing` 函数检查 `string` 向量中的哪些元素是缺失值。

```str = ["A" "B" missing "D" "E" missing]; ind = ismissing(str)```
```ind = 1x6 logical array 0 0 1 0 0 1 ```

`strvals = str(~ind)`
```strvals = 1x4 string "A" "B" "D" "E" ```