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:
MATLAB stores matrices in memory as a column vector. The position of each element in this vector is known as its linear index (Fig. 1). To use linear indexing, specify the linear index of the target element.
In the indexing expression use a scalar to denote a single element, or a set of indices to denote multiple elements. To create a set of indices, use the colon operator (i.e.
:) or the concatenation operator (i.e.
% Sum of the first and the last element in A partialSum = A(1) + A(6); % 1 + 4 = 5
% Elements in the second row secondRow = A(2:2:6);
secondRow = 3 6 4
% Elements from the second to the third column lastTwoCols = A(3:6);
lastTwoCols = 5 6 2 4
% Elements in the first and the third column borderCols = A([1,2,5,6]);
borderCols = 1 3 2 4
% Elements in the second row but in the first and the third column target = A([2,6]);
target = 3 4
% All elements allElements = A(:);
allElements = 1 3 5 6 2 4
I recommend the following books to learn more on linear indexing in MATLAB:
This book was the winner of a Textbook Excellence Award. Linear indexing, and other indexing methods, 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 other tutorials in this series.
- Subscript Indexing in MATLAB
- How Does MATLAB Store 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 of random numbers having three rows, four columns, and two planes.
Use linear indexing to get the elements in the:
- First row of the first plane
- Last three columns of the first plane
- Last two rows of the second plane
- Intersection of the last two rows with the first two columns of the second plane
- Positions whose linear index is an even number
A possible solution could be:
doc rand; X = rand(3,4,2); % Clause 1 clause1Result = X(1:3:10); % Clause 2 clause2Result = X(4:12); % Clause 3 clause3Result = X([14:3:23,15:3:24]); % Clause 4 clause4Result = X([14,15,17,18]); % Clause 5 clause5Result = X(2:2:24);
I hope you have learned how to use linear indexing in MATLAB. The source code developed in this tutorial is available at this page.