Additionally to the functionality provided in the regular sub2ind, following two usage cases are provided:
IND = SUB2IND(SIZ,C), where C is a column vector of length R, returns the linear index equivalent to the subscript of rank R for an array of size SIZ.
IND = SUB2IND(SIZ,M), where M is a R x N matrix, returns the N linear indices equivalent to the N subscripts of rank R in the columns of M for an array of size SIZ.
The only thing to keep in mind is that – like many MATLAB functions - it operates on columns.
Here are variations of the examples provided in the help:
## Example 1
rand('state', 0); % Initialize random number generator.
A = rand(3, 4, 2)
sub2ind(size(A), [2 1 2]') == sub2ind(size(A), 2, 1, 2)
## Example 2
sub2ind(size(A), [2 4]') == sub2ind(size(A), 2, 4)
## Example 3
B = [3 2 3 1 2; 3 4 1 3 4; 2 1 2 2 1];
sub2ind(size(A), B) == sub2ind(size(A), [3 2 3 1 2], [3 4 1 3 4], [2 1 2 2 1])
This implementation is vectorized – in contrast to the original one – and therefore in the case of matrix and column vector input almost guaranteed to be faster than the original, while with traditional input arguments it makes just one additional call to cell2mat.
It strives to provides the same safety checks as the original.
One difference to the original is that the latter would throw an error on trivial/pathological calls where length(SIZ) < 2 like:
sub2ind(5, [1 2 3])
while this version just outputs the expected [1 2 3].
Lorenzo (2022). Augmented version of sub2ind (https://www.mathworks.com/matlabcentral/fileexchange/36458-augmented-version-of-sub2ind), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!