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?
end:-1
.. ??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.
First Idea:
The end:-1:1
expression seemed to me like a loop. So -1, 0, 1 => **3x Elements**
?
But when I type
A(1,end:3)
it only shows me the 3rd row.
Second Idea:
A(end:-1:1,1)
It shows me the inverted 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!
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 : .
A(3, 2)
is the element in the 3,2 position (third row, second column) of AA(1, :)
is equivalent to A(1, 1:size(A, 2))
and A(1, 1:end)
and is the first row of A
A(:, 1)
is equivalent to A(1:size(A, 1), 1)
and A(1:end, 1)
and is the first column of A
A(:)
is equivalent to A(1:numel(A))
and is a single column containing all elements of A