Pergunta

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

Foi útil?

Solução

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.

Outras dicas

First the general stuff: end is just a placeholder for an index, namely the last position in a given array dimension. For instance, for an arbitrary array A(end,1) will pick the last element in column 1, and A(1,end) will pick the last element in the first row.

In your example, A(end, end-2) picks an element in the last row two columns before the last one.

To interpret a statement such as

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

it might help to substitute end with the actual index of the last row/column elements, so this is equivalent to

A(2:3, 4:-2:1)

Furthermore 4:-2:1 is equivalent to the list 4,2 since we are instructing to make the list starting at 4, decreasing in steps of 2, up to (minimum) 1. So this is equivalent to

A([2 3],[4 2])

Finally, the following combination of indices is implied by A([2 3],[4 2]):

 A(2,4)   A(2,2)
 A(3,4)   A(3,2)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top