Search code examples
arraysmatlabmatrix-indexing

Matlab : Matrix indexing Logic


i am doing very simple Matrix indexing examples . where code is as give below

>> A=[ 1 2 3 4 ; 5 6 7 8 ; 9 10 11  12  ]

A =

     1     2     3     4
     5     6     7     8
     9    10    11    12

>> A(end, end-2)   

ans =

    10

>> A(2:end, end:-2:1)

ans =

     8     6
    12    10

here i am bit confused . when i use A(end, end-2) it takes difference of two till first column and when there is just one column left there is no further processing , but when i use A(2:end, end:-2:1) it takes 6 10 but how does it print 8 12 while there is just one column left and we have to take difference of two from right to left , Pleas someone explain this simple point


Solution

  • The selection A(end, end-2) reads: take elements in last row of A that appear in column 4(end)-2=2.

    The selection A(2:end, end:-2:1) similarly reads: take elements in rows 2 to 4(end) and starting from last column going backwards in jumps of two, i.e. 4 then 2.

    To check the indexing, simply substitute the end with size(A,1) or size(A,2) if respectively found in the row and col position.