Create a matrix using the following code:
A = [1, 5, 2; 3, 6, 4];
A = 1 5 2 3 6 4
MATLAB supports three ways to reference elements in a matrix:
To convert linear indices to their equivalent subscripts, use the function
ind2sub. For the opposite, use
[rowSub,colSub,dim3Sub,...,dimNSub] = ind2sub(siz,linearInd); linearInd = sub2ind(siz,rowSub,colSub,dim3Sub,...,dimNSub);
ind2sub takes as input the size of the matrix, and the linear indices, and returns the corresponding subscripts grouped by dimension.
sub2ind takes as input the size of the matrix, and the subscripts grouped by dimension, and returns the corresponding linear indices.
% Get subscripts equivalent to A(5) and A(6) [rowSub,colSub] = ind2sub(size(A),[5,6]);
rowSub = 1 2
colSub = 3 3
% Get linear indices equivalent to A(1,3) and A(2,3) linearInd = sub2ind(size(A),[1,2],[3,3]);
linearInd = 5 6
Note: In the case of
sub2ind, the subscript vectors must have the same size, and this size determines the shape of the output.
I recommend the following books to learn more on linear indexing and subscript indexing in MATLAB:
This book was the winner of a 2017 Textbook Excellence Award. Linear indexing and subscript indexing are explained clearly in the second chapter.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The fourth chapter is completely dedicated to matrix manipulation.
I also recommend the following pages in the MATLAB help documentation, and the other tutorials in this series.
doc ind2sub; doc sub2ind;
- Subscript Indexing in MATLAB
- How MATLAB Stores Matrices in Memory
- Linear Indexing in MATLAB
- How to Convert Linear Indices to Subscripts and Viceversa in MATLAB
- MATLAB end Keyword in Matrix Indexing Expressions
- Logical Indexing in MATLAB
- A Deeper Look on Logical Indexing in MATLAB
- MATLAB Colon Operator in Matrix Indexing Expressions
Consult the help documentation of the
rand function. Create a matrix
X of random numbers having three rows, four columns, and two planes.
- Calculate the subscripts equivalent to
- Calculate the linear indices equivalent to
In all prior cases, use only one statement per clause, and visually check that the subscripts and linear indices reference the same data.
A possible solution could be:
doc rand; X = rand(3,4,2); % Clause 1 [rowSub,colSub,planeSub] = ind2sub(size(X),[2,6,15]); % Clause 2 linearInd = sub2ind(size(X),[1,3,2],[1,4,3],[1,1,2]); % To visually check, see notes in the source code.
I hope you have learned how to convert linear indices to subscripts, and viceversa, in MATLAB. The source code developed in this tutorial is available at this page.