Mixing subscripts with linear indices
77 次查看(过去 30 天)
显示 更早的评论
Generally speaking, I have found that it has always been possible to mix subscript and linear array indexing, as long as the indexing syntax is in the form,
A(subscript_1,subscript_2,...,subscript_n, linear_index).
For example, given,
A = reshape((1:24)*3, [4, 3, 2]);
all of the following are valid ways of indexing the final element in A,
A(4,3,2)
A(4,6)
A(24)
However, I haven't been able to find documentation of this, except of course for the trivial case where n=0. Is it officially supported behavior?
1 个评论
Paul
2025-11-29,4:01
Same example as above, with other cases
A = reshape((1:24)*3, [4, 3, 2])
The linear index can be a vector
A(:,[3 5])
Or a colon
A(2,:)
A(:,:)
Or even an array, which gets stretched into a vector index
A(:,[1:2;1:2])
I too can't find relevant documentation.
采纳的回答
Stephen23
2025-11-29,5:32
编辑:Stephen23
2025-11-29,5:53
When fewer subscripts are provided than non-singleton dimensions then all trailing dimensions are "folded" into the last subscript. This is explicitly described in the documentation section entitled "Indexing with Fewer Subscripts Than Array Dimensions":
Loren Shure also wrote: "Indexing with fewer indices than dimensions If the final dimension i<N, the right-hand dimensions collapse into the final dimension."
Note that linear indexing is really just a side-effect of this. An earlier discussion on this:
6 个评论
Stephen23
2025-11-29,18:55
"AFAICT, the information on the page linked by @Stephen23 entitled "Detailed Rules for Array Indexing" was only added to the documentation in R2025a"
Correct. Previously the only location that I recall was Loren's blog (from 2006).
Paul
2025-12-1,16:49
编辑:Paul
2025-12-1,17:49
I'm inordinately annoyed that "Detailed Rules for Array Indexing" is only considered to be a "Related Topic" to "Array Indexing." Seems like "detailed rules" would actually be fundamental to the discussion of array indexing. If the doc authors thought the detailed rules would add too much information to the Array Indexing page, then the detailed rules should be linked directly from the main discussion on that page, instead of or in addition to being a "Related Topic."
Also, it's rather disappointing that such a core functionality for a Matrix Laboratory is only showing up in the doc now, about 20 years after it was (informally) published, and I suspect it's been part of Matlab since the introduction of N-D arrays.
And if they were going to add the Detailed Rules, then why not add all of them? In addition to the example I showed above, Loren's blog shows:
" Indexing with one array C = A(B) produces output the size of B unless both A and B are vectors."
I think I knew about this, but I don't see it on either of the two doc pages in this discussion.
更多回答(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!