FreeMat

- Main Page
- Related Pages

SUB2IND Convert Multiple Indexing To Linear Indexing

Section: Elementary Functions

# Usage

The `sub2ind` function converts a multi-dimensional indexing expression into a linear (or vector) indexing expression. The syntax for its use is

       y = sub2ind(sizevec,d1,d2,...,dn)

where `sizevec` is the size of the array being indexed into, and each `di` is a vector of the same length, containing index values. The basic idea behind `sub2ind` is that it makes

      [z(d1(1),d2(1),...,dn(1)),...,z(d1(n),d2(n),...,dn(n))]

equivalent to

      z(sub2ind(size(z),d1,d2,...,dn))

where the later form is using vector indexing, and the former one is using native, multi-dimensional indexing.

# Example

Suppose we have a simple `3 x 4` matrix `A` containing some random integer elements

    --> A = randi(ones(3,4),10*ones(3,4))

    A =
      2  3  2  3
     10  2  4  8
      5 10  1  2

We can extract the elements `(1,3),(2,3),(3,4)` of `A` via `sub2ind`. To calculate which elements of `A` this corresponds to, we can use `sub2ind` as

    --> n = sub2ind(size(A),1:3,2:4)

    n =
      4  8 12

    --> A(n)

    ans =
     3 4 2