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 = 
  <int32>  - size: [3 4]
 
Columns 1 to 4
  7   9   7   2  
  8   4   8   2  
  6   7  10   5  

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 = 
  <int32>  - size: [1 3]
 
Columns 1 to 3
  4   8  12  
--> A(n)
ans = 
  <int32>  - size: [1 3]
 
Columns 1 to 3
 9  8  5