Arrays 线性索引、逻辑索引等等
我们习惯于在Matlab中使用不同形式的索引:Arrays 线性索引、逻辑索引等等,arrays,matlab,matrix,matrix-indexing,Arrays,Matlab,Matrix,Matrix Indexing,我们习惯于在Matlab中使用不同形式的索引: 标准(沿每个维度使用整数) 逻辑(使用逻辑值) 线性(使用单个索引遍历具有多个维度的数组) 乍一看,这些形式似乎是排他性的:索引要么是标准的,要么是逻辑的,要么是线性的。然而,有时这几种形式之间似乎是混合的。比如说, >> A = magic(3) A = 8 1 6 3 5 7 4 9 2 >> A(A>5) ans = 8
- 标准(沿每个维度使用整数)
- 逻辑(使用逻辑值)
- 线性(使用单个索引遍历具有多个维度的数组)
>> A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>> A(A>5)
ans =
8
9
6
7
这是逻辑索引,对吗?但它也有一些线性索引的特性,因为返回了一个列向量。事实上,逻辑索引A>5
与线性索引find(A>5)
具有相同的效果
作为第二个例子,考虑
>> A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>> A(1:2, [true false true])
ans =
8 6
3 7
在此表达式中,标准(整数值)索引用于第一个坐标,逻辑索引用于第二个坐标
这些例子(以及实践中出现的更复杂的例子)提出了以下问题:
- Matlab中有哪些类型的索引?
- 它们如何组合?
- 应该如何引用它们?
大小
)确定为索引变量形状的函数。罗兰·舒尔(Loren Shure)在这方面发表了一篇很好的文章
下面的说明重点介绍对数值数组的索引,但它可以应用于带有括号或大括号索引的单元格数组,输出类型(单元格数组或逗号分隔列表)有明显变化。这将在最后简要讨论
数值数组中的索引类型
索引可以根据以下两个属性进行分类
- 纯多维索引为数组的每个维度指定一个索引变量。单个索引有时在Matlab文档中称为下标(参见示例)
- 纯线性索引指定一个索引变量,该变量跨所有维度遍历数组(这可以被视为所有维度合并为一个)。正如我们所知,遍历是先沿列,然后沿行,然后沿第三个dim切片,等等(所谓的)
- 部分线性索引:给定具有
维度的数组,m+n
,可以为第一个n>=2
维度指定m
索引变量(因此在这些维度中使用多维索引),为最后一个m
维度指定一个索引变量,它仅被解释为这些维度的线性索引(最后一个n
维度折叠为一个)n
- 如果索引变量包含正整数,则为整数值
A(:,:,1) =
8 1 6
3 5 7
4 9 2
A(:,:,2) =
17 10 15
12 14 16
13 18 11
C(:,:,1) =
[8] [1] [6]
[3] [5] [7]
[4] [9] [2]
C(:,:,2) =
[17] [10] [15]
[12] [14] [16]
[13] [18] [11]
>> A([1 2], 2, 2)
ans =
10
14
>> A([2 5:7])
ans =
3 5 9 6
>> A([1 2], 2:4)
ans =
1 6 17
5 7 12
>> A([true false true], [false true true], 2)
ans =
10 15
18 11
>> A([1 2], 2, 2)
ans =
10
14
>> A([2 5:7])
ans =
3 5 9 6
>> A([1 2], 2:4)
ans =
1 6 17
5 7 12
>> A([true false true], [false true true], 2)
ans =
10 15
18 11
>> A([1 2], 2, 2)
ans =
10
14
>> A([2 5:7])
ans =
3 5 9 6
>> A([1 2], 2:4)
ans =
1 6 17
5 7 12
>> A([true false true], [false true true], 2)
ans =
10 15
18 11
>> A([true true false], [false true false], [false true])
ans =
10
14
>> A([false true false false true true true])
ans =
3 5 9 6
>> A([true true false], [false true true true false false])
ans =
1 6 17
5 7 12
有趣的是,逻辑值的数量可能小于甚至大于索引所指维度中的大小:
>> A([true true], [false true false false], [false true])
ans =
10
14
缺失值被解释为false
,剩余值必须为false
,否则将发生错误。例如,参见或>> A([true true false], [false true false], [false true])
ans =
10
14
>> A([false true false false true true true])
ans =
3 5 9 6
>> A([true true false], [false true true true false false])
ans =
1 6 17
5 7 12
(请注意,索引向量中遗漏了11个尾随false
值。)>> A([true true false], [false true false], [false true])
ans =
10
14
>> A([false true false false true true true])
ans =
3 5 9 6
>> A([true true false], [false true true true false false])
ans =
1 6 17
5 7 12
>> A([1 2], 2, 2)
ans =
10
14
>> A([2 5:7])
ans =
3 5 9 6
>> A([1 2], 2:4)
ans =
1 6 17
5 7 12
>> A([true false true], [false true true], 2)
ans =
10 15
18 11
>> A([1 2], [true false true false true false])
ans =
8 6 10
3 7 14
C=num2cell(A)