0

I have a matrix A

A =

 1     2     3     4     5
 6     7     8     9    10
11    12    13    14    15
16    17    18    19    20

i have another matrix to specify the indices

index =

 1     2
 3     4

Now, i have got third matrix C from A

C = A(index)

C =

 1     6
11    16

Problem: I am unable to understand how come i have received such a matrixC. I mean, what is logi behind it?

user2756695
  • 676
  • 1
  • 7
  • 22
  • 1
    See also this [Q&A](http://stackoverflow.com/questions/21413164/is-matlab-row-specific-or-column-specific). – chappjc Mar 05 '14 at 18:13

1 Answers1

4

The logic behind it is linear indexing: When you provide a single index, Matlab moves along columns first, then along rows, then along further dimensions (according to their order).

So in your case (4 x 5 matrix) the entries of A are being accessed in the following order (each number here represents order, not the value of the entry):

 1     5     9    13    17
 2     6    10    14    18
 3     7    11    15    19
 4     8    12    16    20

Once you get used to it, you'll see linear indexing is a very powerful tool.

As an example: to obtain the maximum value in A you could just use max(A(1:20)). This could be further simplified to max(A(1:end)) or max(A(:)). Note that "A(:)" is a common Matlab idiom, used to turn any array into a column vector; which is sometimes called linearizing the array.

See also ind2sub and sub2ind, which are used to convert from linear index to standard indices and vice versa.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147