Can someone explain to me why this sub-array behaves this way?
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Walter Roberson
on 10 Feb 2018
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
More Answers (2)
James Tursa
on 10 Feb 2018
Edited: James Tursa
on 10 Feb 2018
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 Comments
Peter
on 10 Feb 2018
Great answer, James! Kevin, perhaps you intended this?
>> arr([2 3],[2 3])
ans =
5 6
8 9
0 Comments
See Also
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!