Why does accessing a multi-dimensional array with fewer indices than its total dimensions not result in an error in MATLAB R2022b?
Show older comments
I constructed a multi-dimensional array in MATLAB and called it with fewer indices. I was expecting to get an error message for the missing index, but the script was executed without any error message. Here's an example:
>> size(Pcc)
ans =
5 6 5 6 6
>> Pcc(1,1,1,1)
ans =
0.7854
Is this a bug?
Accepted Answer
More Answers (1)
James Tursa
on 1 Sep 2023
Edited: James Tursa
on 1 Sep 2023
The accepted answer is misleading. When you access a multi-dimensional array with fewer indexes than its total dimensions, MATLAB treats the array as if it had only the dimensions you used, with the last dimension being all the actual remaining dimensions bunched into one dimension in the same memory order. E.g.,
A = reshape(1:24,2,3,4)
A(2,3)
A(2,5)
So, why did that last A(2,5) work? Clearly 5 is greater than the actual 2nd dimension value 3. It worked because the (2,3,4) dimensions of A are treated as if the dimensions are (2,3*4) = (2,12) when accessing with only two indexes. The last part is simply accessed in memory order. It is as if you did a temporary reshape(A,2,12) first:
reshape(A,2,3*4)
And from this you can see that the A(2,5) element is indeed 10 when A is treated as a temporarily reshaped 2D matrix.
Bottom line is when you access a multi-dimensional array using fewer indexes than there are dimensions, MATLAB treats the array as a reshaped array using the number of dimensions that matches the number of indexes you used with the last dimension being the product of all trailing dimensions. Another example:
A = reshape(1:36,3,2,3,2)
A(2,10)
reshape(A,3,2*3*2)
Again, you can see that the A(2,10) spot matches what you would expect from the reshaped matrix.
2 Comments
Note that the indexing documentation does not mention this behavior, but it is explained here:
An interesting corollary of this is that linear indexing is just an edge-case of subscript indexing.
Haman
on 6 Nov 2023
Thank you for pointing out the flaw in the posted answer. We've updated the answer to include your suggested change.
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!