
Extracting a submatrix from a matrix in Matlab
In this online lesson, I will explain how to extract submatrices from a matrix in Matlab.
What is a submatrix? A submatrix is a matrix that is contained within another matrix. A submatrix always has fewer rows and/or columns than the matrix that contains it. Here's an example of a submatrix (or "submatrix") of matrix M.
Here's a practical example.
First, type the command M=[1 2 3 4;5 6 7 8;9 10 11 12; 13 14 15 16] to create a matrix.
This is a square matrix with four rows and four columns.
Type M([1:2],[1:2]) to extract the first and second columns [1,2] along with the first and second rows [1,2] from matrix M.
This command extracts the 2x2 square submatrix.
Now type M([1:2],[1:3]) to extract the first three columns [1:3] along with the first two rows [1:2] of matrix M.
This command extracts a rectangular 2x3 submatrix.
How do you extract a submatrix if the rows and columns are not adjacent?
If the rows or columns are not adjacent, write down the columns or rows you want to extract without using the colon as a separator.
For example, type M([1 4],[1:3]) to extract the first and fourth row [1 4] along with the first three columns [1:3].
This command extracts another 2x3 submatrix of matrix M with different rows.
Note. When you want to select individual columns/rows, you need to separate them with a space or comma. You can also select multiple rows/columns individually within square brackets. For example, type M([1 3 4],[1:3]) to extract the first, third, and fourth rows [1 3 4] along with the first three columns [1:3].