我们习惯于在Matlab中使用不同形式的索引:
乍一看,这些形式似乎是排他性的:索引要么是标准的,要么是逻辑的,或者是线性的。然而,有时这些形式中的几种似乎是混合的。例如,
>> 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在这个表达式中,标准(整数值)索引用于第一个坐标,逻辑索引用于第二个坐标。
这些例子(以及在实践中出现的更复杂的例子)提出了以下问题:
发布于 2015-09-03 15:28:36
在下面的文章中,我使用了术语,我认为它或多或少符合标准的Matlab实践。然而,在某些情况下,我不得不排序-组成一个名称,因为我不知道有一个现有的。请告诉我是否有比我使用的更多的标准名称。
这个答案试图澄清不同类型的索引,以及如何组合它们。另一个不同的问题是如何将输出数组的形状 (size)确定为索引变量形状的函数。这方面的一个好帖子是罗琳·舒尔( Loren )的http://blogs.mathworks.com/loren/2006/08/09/essence-of-indexing/。
接下来的描述侧重于数字数组的索引,但它可以应用于带有括号或大括号的单元数组,输出类型有明显的变化(单元格数组或逗号分隔列表)。最后将对此进行简要讨论。
数值数组中的索引类型
考虑到以下两个属性,可以对索引进行分类。
- Pure **multidimensional** indexing specifies an index variable for each dimension of the array. The individual indices are sometimes referred to as **subscripts** in Matlab documentation (see for example [`sub2ind`](http://es.mathworks.com/help/matlab/ref/sub2ind.html)).
- Pure **linear** indexing specifies a single index variable that traverses the array across all dimensions (this can be viewed as if all dimensions collapse into one). As we know, the traversal is along columns first, then along rows, then along third-dim slices, etc (so-called [column-major order](https://en.wikipedia.org/wiki/Row-major_order)).
- **Partially linear** indexing: given an array with `m+n` dimensions, `n>=2`, one can specify `m` index variables for the first `m` dimensions (thus using multidimensional indexing in those dimensions) and one index variable for the last `n` dimensions, which is interpreted as a linear index for those dimensions only (the last `n` dimensions collapse into one).
- It is **integer-valued** if the index variable contains positive integers;
- It is **logical** if the index variable contains logical values.
分类标准1和2是independent.从标准1的角度看,指标的范畴与标准2中的分类没有关系,所有的组合都是可能的。
因此,根据上述分类,有6种基本类型的索引。为了澄清,下面是每一个例子。所有示例都使用数组A = cat(3, magic(3), 9+magic(3)),即,
A(:,:,1) =
8 1 6
3 5 7
4 9 2
A(:,:,2) =
17 10 15
12 14 16
13 18 11false,剩余值必须是false,否则会发生错误。例如,参见这页是Mathworks写的或乔纳斯的回答。false值。)在具有多个索引变量的多维或部分线性索引中,每个索引变量可以是独立的整数值或逻辑变量。这就产生了不同的混合类型。例如:
如果正在被索引的数组是稀疏矩阵,那么上述所有内容都仍然适用,只是矩阵不存在部分线性索引;当然,结果也是稀疏的。
单元阵列索引
为数值数组描述的所有类型的索引都可以应用于单元格数组,还有一个额外的考虑因素。单元格数组可以用括号或大括号索引。在第一种情况下,索引的结果是一个单元数组。第二部分是单元格内容的逗号分隔列表。
例如,假设前面示例中使用的数值数组被转换为单元格数组C = num2cell(A),即,
C(:,:,1) =
[8] [1] [6]
[3] [5] [7]
[4] [9] [2]
C(:,:,2) =
[17] [10] [15]
[12] [14] [16]
[13] [18] [11]然后,上面示例8中使用的索引将产生单元格数组。
>> C([1 2], [true false true false true false])
ans =
[8] [6] [10]
[3] [7] [14]而使用大括号则会产生逗号分隔的列表。
>> C{[1 2], [true false true false true false]}
ans =
8
ans =
3
ans =
6
ans =
7
ans =
10
ans =
14 接收信息/ TL;DR
逻辑索引和线性索引不是唯一的索引类型。相反,它们是索引的两个独立特性。“逻辑”指的是索引值的类型,“线性”表示有几个维度被折叠和索引为一个。这两个特性可以同时发生。
https://stackoverflow.com/questions/32379805
复制相似问题