2016-08-15 15 views
0
data = reshape(1:21504,[256,4,21]); 
data(:,5:4:end) 

我測試的一些指標,如:這個指數在MATLAB中的含義是什麼?

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)是確定的。

那麼這裏發生了什麼?
我該如何理解這種機制?

+1

在[MATLAB文檔](http://mathworks.com/help/matlab/ref/colon.html)中有一些例子, – serial

回答

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

data(:, 5:4:end)將訪問的所有元素中的data第一維和從索引5每4個索引開始,直到在data第二維度的最後一個索引。該索引技術的語法可以這樣解釋:

data(startIndex:step:endIndex) 

如果data有多個維度比你用於索引,這將承擔:爲以後每一個維度。

0

綜上所述我的問題:

data=reshape(1:24,2,3,4) 

數據(:,:,1)=

1  3  5 
2  4  6 

數據(:,:,2)=

7  9 11 
8 10 12 

數據(:,:,3)=

13 15 17 
14 16 18 

數據(:,:,4)=

19 21 23 
20 22 24 

使用這個例子,你可以知道Matlab在做什麼:

個數據(:,1)

ANS =

1 
2 

數據(:,12)

ANS =

23 
24 

數據(:,[1,12])

ans =

1 23 
2 24 

數據(:,5:4:結束)

ANS =

9 17 
10 18 

如果使用data(:,13),它引發錯誤。

相關問題