Can someone explain to me why this sub-array behaves this way?
2 次查看(过去 30 天)
显示 更早的评论
I'm new to Matlab and don't understand why an array
arr = [1 2 3; 4 5 6; 7 8 9]
gives an answer of
ans = [6 6; 6 6]
when you ask for
arr([2 2], [3 3])
If someone could explain this to me it would be greatly appreciated.
0 个评论
采纳的回答
Walter Roberson
2018-2-10
When you index, you get every combination of indices. For example, arr(1,:) gives every combination of 1 in the first index and all the valid column numbers in the second index -- all of row 1. arr(1:2,:) would give every combination of either 1 or 2 for the first index and all the valid column numbers for the second index -- all of rows 1 and 2.
It is every combination -- not every unique combination. So arr([1 1],:) would give all of row 1 twice.
When you index arr([2 2], [3 3]), treat it like arr([A B], [C D]), where you get every combination arr(A,C), arr(B, C), arr(A,D), arr(B,D), even though some of those are the same as the others. With A and B both being 2 and C and D both being 3, you end up selecting arr(2,3) four times
更多回答(2 个)
James Tursa
2018-2-10
编辑:James Tursa
2018-2-10
The (i,j)'th element of the result is made up of the (row_index(i),col_index(j)) element of the source. Since you have two row indexes (both equal to 2), and two column indexes (both equal to 3), you get a 2x2 result where all of the elements are made up of the (2,3) element of the source. E.g.,
arr([a b],[c d])
will be a 2x2 matrix as follows
[ arr(a,c) arr(a,d)
arr(b,c) arr(b,d) ]
0 个评论
Peter
2018-2-10
Great answer, James! Kevin, perhaps you intended this?
>> arr([2 3],[2 3])
ans =
5 6
8 9
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!