sub2ind

sub2ind(dims, i, j, k...) -> index

The inverse of ind2sub, returns the linear index corresponding to the provided subscripts

Examples

  1. Convert subscripts to linear index:

    julia> dims = (3, 4, 2);
    julia> sub2ind(dims, 2, 3, 1)
    23

    This example converts the subscripts (2, 3, 1) to the corresponding linear index in a multidimensional array with dimensions (3, 4, 2).

  2. Handle 2-dimensional array:

    julia> dims = (5, 6);
    julia> sub2ind(dims, 4, 2)
    20

    It calculates the linear index for the given subscripts (4, 2) in a 2-dimensional array.

  3. Handle larger dimensions:

    julia> dims = (10, 10, 10, 10);
    julia> sub2ind(dims, 3, 5, 7, 9)
    793

    This example demonstrates the usage of sub2ind with larger dimensions. It converts the subscripts (3, 5, 7, 9) to the corresponding linear index.

  4. Handle edge cases with single-dimensional array:
    julia> dims = (7,);
    julia> sub2ind(dims, 4)
    4

    It correctly handles the case of a single-dimensional array, where the linear index is the same as the provided subscript.

Common mistake example:

julia> dims = (2, 3);
julia> sub2ind(dims, 3, 2, 1)
ERROR: DimensionMismatch("subscripts (3, 2, 1) do not match array dimensions (2, 3)")

In this example, the provided subscripts do not match the dimensions of the array. It's important to ensure that the number of subscripts matches the number of dimensions in the array.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: