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?

1
  • 1
    See also this Q&A. Commented Mar 5, 2014 at 18:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.