Augmented version of sub2ind
### Usage
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.
### Examples
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])
### Implementation
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].
Cite As
Lorenzo (2024). Augmented version of sub2ind (https://www.mathworks.com/matlabcentral/fileexchange/36458-augmented-version-of-sub2ind), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform Compatibility
Windows macOS LinuxCategories
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.