matlabmatrixsyntaxprogramming-languagesmatrix-indexing

Matlab Matrixaddress


During my course I came across that expression:

A(:,end:-1:1)

I have trouble to understand and read the morphemic structure of the 2nd Operand "end;-1;1"


Lets take the example:

A=[1 2 3; 4 5 6; 7 8 9]

I am aware of:

A(:).. Outputs [1 2 3; 4 5 6; 7 8 9] as rows. Operator is :.
A(1,:).. Outputs [1 2 3; 4 5 6; 7 8 9] as columns Operator is , then , .
A(:,1).. Outputs [1 2 3; 4 5 6; 7 8 9] as rows. Operator is , beforehand : .

A(:,end:-1:1)

Output in Matlab show me: 3x3 Matrix.

How am I supposed to read the structure?

  1. Graphem: : ..show me the rows,
  2. Graphem: end:-1 .. ??
  3. Graphem: :1 ..

Somehow ":" was for me the operator for show all of the elements.

It makes sense to me that the "Operand1 , Operand2" shows me the 2 Dimensional Matrix.

My background:
I am a undergraduate student from the field of language.
I build in my freetime the 8-Bit Sap1 according Ben Eater.
So I am familiar with program memory or instruction memory.
I understand only the result, but not how it is achieved by the MATLAB compiler.
Someone said to me that the "Matrixaddressing is somehow optimized". Looking forward to a helpful answer in each step. :)

Thanks in advance!


Solution

  • The end keyword in matrix indexing indicates index of last element in the corresponding dimension. So, A(:,end:-1:1) simply means A(:, size(A, 2):-1:1), which in you example (A=[1 2 3; 4 5 6; 7 8 9]), is equivalent to A(:, 3:-1:1).

    But to understand what it does, you need to know what 3:-1:1 does. It creates a subrange. You already know 1:3 creates [1, 2, 3]. 1:3 is simplified form of 1:1:3: rangeStrart:increment:rangeEnd. Now, 3:1 or 3:1:1 creates an empty vector, because rangeStart is greater than rangeEnd. To create [3, 2, 1] you need to use a negative step: 3:-1:1.

    So, A(:,end:-1:1) means A(:, [3, 2, 1]), which inverts order of rows of A. Also, A(:,end:3) means A(:, 3:3) and eventually A(:, 3), which returns 3rd row of A.

    Edit: about your misunderstandings, addressed by @CrisLuengo

    I am aware of:
    A(:).. Outputs [1 2 3; 4 5 6; 7 8 9] as rows. Operator is :.
    A(1,:).. Outputs [1 2 3; 4 5 6; 7 8 9] as columns Operator is , then , .
    A(:,1).. Outputs [1 2 3; 4 5 6; 7 8 9] as rows. Operator is ,beforehand : .