Understanding indexing and the colon operator
20 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
Stephen23
2019 年 1 月 9 日
編集済み: Stephen23
2019 年 1 月 9 日
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.
3 件のコメント
Stephen23
2019 年 1 月 9 日
編集済み: Stephen23
2019 年 1 月 9 日
Check your addition: for n=3 the code end-3+1 == end-2, because -3+1 == -2, not -4.
The +1 gives exactly the last n columns. Consider these:
- end-0:end will give the last column only (equivalent to end by itself),
- end-1:end will give the last two columns,
- end-2:end will give the last three columns,
- end-3:end will give the last four columns,
- etc.
Notice the pattern: the number of returned columns is always 1 more than the number subtracted from end. So if the number subtracted from end is n and you want n columns, it is neccesary to +1.
Shubham Gupta
2019 年 1 月 9 日
When n = 3 ,' end-n+1' will become 'end-2' not 'end-4'. Also, 'end-4' is NOT fourth from last it actually is fifth from the last.
その他の回答 (1 件)
Shubham Gupta
2019 年 1 月 9 日
編集済み: Shubham Gupta
2019 年 1 月 9 日
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 件のコメント
Stephen23
2019 年 1 月 9 日
編集済み: Stephen23
2019 年 1 月 9 日
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.
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!