MATLAB: Understanding indexing and the colon operator

indexing

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

Best Answer

The end keyword simply refers to the last column (it can also be used for rows, etc.):
In your example it is basically equivalent to this:
C = size(A,2); % i.e. the last column
A(1:n,C-n+1:C);
but clearly saves a bit of typing and makes things neater. If C is the last column, then C-n+1:C will give the last n columns.