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 use subscript indexing, specify the index of the target element in each dimension. The first index denotes row, the second index denotes column, the third index denotes plane, and so on (Fig. 1).
% Sum of the first and the last element in A partialSum = A(1,1) + A(2,3); % 1 + 4 = 5
% Elements in the second row secondRow = A(2,:);
secondRow = 3 6 4
% Elements from the second to the third column lastTwoCols = A(:,2:3);
lastTwoCols = 5 2 6 4
% Elements in the first and the third column borderCols = A(:,[1,3]);
borderCols = 1 2 3 4
% Elements in the second row but in the first and the third column target = A(2,[1,3]);
target = 3 4
I recommend the following books to learn more on subscript indexing in MATLAB:
This book was the winner of a 2017 Textbook Excellence Award. Subscript 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 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 of random numbers having three rows, four columns, and two planes.
Use subscript 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
- First row of each plane
A possible solution could be:
doc rand; X = rand(3,4,2); % Clause 1 clause1Result = X(1,:,1); % Clause 2 clause2Result = X(:,2:4,1); % Clause 3 clause3Result = X(2:3,:,2); % Clause 4 clause4Result = X(2:3,1:2,2); % Clause 5 clause5Result = X(1,:,:);
I hope you have learned how to use subscript indexing in MATLAB. The source code developed in this tutorial is available at this page.