Understanding indexing and the colon operator
Show older comments
I am working on a problem for class and I am trying to understand the solution to a practice problem. The function code is below. I am not understanding the end-n+1:end portion and how that returns the top right columns of a matrix. I understand that 1:n returns the 1st through n rows of the matrix. If someone could explain this clearly to me I would appreciate it. Thanks!
function A = top_right(A,n)
A = A(1:n,end-n+1:end);
end
Accepted Answer
More Answers (1)
Shubham Gupta
on 9 Jan 2019
Edited: Shubham Gupta
on 9 Jan 2019
When you use 'end' for indexing, it means that you want to use 'last' index of the array. So, for e.g. if A is a 3x4 matrix and n = 2 then,
A(1:n,end-n+1:n) % Edited from A(1:n,end-1+n ) [ Thanks Stephen ]
will mean
A(1:2,4-2+1:4)
Note: 'end' = 4( number of columns ) when writing on column side and 'end' = 3 (number of rows ) when writing on row side
1 Comment
A(1:n,end-1+n:n)
For any n>1 this will return nothing at all because end-1+n will be beyond the last column, and for n==1 it returns nothing unless A has only one column. Your example:
A(1:2,4-1+2:4)
is actually equivalent to this:
A(1:2,5:4)
which is equivalent to this:
A(1:2,[])
This is not what the question asked about, you have mixed up the order of the terms.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!