简体   繁体   中英

Using a vector as an index to a matrix in matlab

I understand the general idea, but given a 3 dimensional vector x, what does the following mean?

x(:,:,[2:end,end])

I know there are very similar questions, but they are asking for the code to achieve a desired behavior, whereas I need to know what behavior this code specifies.

That code simply makes a new 3D matrix such that we copy slices 2, 3, 4, up until N where N is the last slice of the matrix, and we also replicate the last slice N on top of this and place it at the end of the 3D matrix as the final slice for the output. The vector [2:end end] is important. Doing : over the first two dimensions means that we want all of the rows and all of the columns. For the third argument to index into your matrix, we are specifying a vector of 2:end then an additional end . end is a special keyword in this context that accesses the last possible element in that particular dimension. In this case, end would correspond to the last slice of the matrix. Therefore, doing 2:end means that you wish to access slice 2, 3, up until the last slice, and then you wish to access the last slice one more time.

You can always output what the matrix looks like in the command prompt with some sample inputs. Consider the following 3D matrix:

>> V = reshape(1:24, 4, 2, 3)

V(:,:,1) =

     1     5
     2     6
     3     7
     4     8


V(:,:,2) =

     9    13
    10    14
    11    15
    12    16


V(:,:,3) =

    17    21
    18    22
    19    23
    20    24

Doing:

V(:,:,[2:end end])

gives:

>> V(:,:,[2:end end])

ans(:,:,1) =

     9    13
    10    14
    11    15
    12    16


ans(:,:,2) =

    17    21
    18    22
    19    23
    20    24


ans(:,:,3) =

    17    21
    18    22
    19    23
    20    24

As you can see, we create another 3D matrix such that we omit the first slice, but copy over slices 2, 3, ... up until the last slice N , and then create one more additional slice that copies over slice N .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM