这个索引在MATLAB中的含义是什么?

时间:2016-08-15 08:16:11

标签: matlab octave

data = reshape(1:21504,[256,4,21]);
data(:,5:4:end)

我测试了一些索引,例如:

data(:,5:4:end) ~= data(:,5:4:end,1)
data(:,5:4:end) ~= data(:,1,5:4:end)

那么data(:,5:4:end)是什么意思?

我测试了一些其他索引,例如:

data(1,1) == data(1,1,1)
data(1,1:3) == data(1,1:3,1)

并发现一些奇怪的行为,例如data(1,1:10,1)返回错误,但data(1,1:10)没问题。

那么这里发生了什么? 我怎么能理解这种机制呢?

3 个答案:

答案 0 :(得分:2)

>> size(data)
ans =
256     4    21

data(1,1:10,1)从第一行中选择第1-10列(显式设置所有三个维度),但只有4列。因此错误。

另一方面,

data(1,1:10)使用线性索引,它将维度2和3解释为一个长值的值并选择其前10个值。

线性索引

What does this expression A(14) do?

When you index into the matrix A using only one subscript, MATLAB treats A as if its elements were strung out in a long column vector, by going down the columns consecutively, as in:

          16
           5
           9
         ...
           8
          12
           1

The expression A(14) simply extracts the 14th element of the implicit column vector. Indexing into a matrix with a single subscript in this way is often called linear indexing.

Here are the elements of the matrix A along with their linear indices:
matrix_with_linear_indices.gif

The linear index of each element is shown in the upper left.

From the diagram you can see that A(14) is the same as A(2,4).

The single subscript can be a vector containing more than one linear index, as in:

  A([6 12 15])
  ans =
      11   15   12

Consider again the problem of extracting just the (2,1), (3,2), and (4,4) elements of A. You can use linear indexing to extract those elements:

  A([2 7 16])
  ans =
      5   7   1

That's easy to see for this example, but how do you compute linear indices in general? MATLAB provides a function called sub2ind that converts from row and column subscripts to linear indices. You can use it to extract the desired elements this way:

  idx = sub2ind(size(A), [2 3 4], [1 2 4])
  ans =
      2   7   16
  A(idx)
  ans =
      5   7   1

(从http://de.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html复制)

答案 1 :(得分:1)

data(:, 5:4:end)将访问data的第一维中的所有元素,并从第4个索引的索引5开始,直到data的第二个维度中的最后一个索引。这种索引技术的语法可以解释如下:

data(startIndex:step:endIndex)

如果data的维度多于您用于索引的维度,则此后的每个维度都会假设:

答案 2 :(得分:0)

总结我的问题:

 1     3     5
 2     4     6
  

数据(:,:,1)=

 7     9    11
 8    10    12
     

数据(:,:,2)=

13    15    17
14    16    18
     

数据(:,:,3)=

19    21    23
20    22    24
     

数据(:,:,4)=

 1
 2

使用此示例,您可以了解Matlab正在做什么:

  

数据(:,1)

     

ans =

23
24
     

数据(:,12)

     

ans =

 1    23
 2    24
     

数据(:,[1,12])

     

ans =

 9    17
10    18
     

数据(:,5:4:结束)

     

ans =

data(:,13)

如果您使用{{1}},则会抛出错误。