# How to extract submatrices from a matrix in Matlab and Octave

To extract a submatrix of a matrix in Matlab and Octave type the command

M([row1 row2],[col1 col2])

The command has two parameters

• The first parameter before the comma is a list of rows [row1 row2] or a range of rows [row1: row2] of the sub-array.
• The second parameter after the comma is the list of columns [col1 col2] or the range of columns [col1: col2] of the submatrix.

Note. To indicate a range of rows / columns use the symbol: as a separator. For example [1: 3]. To indicate a list of single rows / columns instead, separate the rows / columns with a space or a comma. For example [1 2 3].

## Examples

Example 1

Create a 3x3 matrix

>> M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
M =
1 2 3
4 5 6
7 8 9

Extract the submatrix with the first two rows [1: 2] and the last two columns [2: 3]

>> M([1:2],[2:3])
ans =
2 3
5 6

The result is a 2x2 submatrix

Example2

Extract the submatrix using the first and last row [1 3] and the last two columns [2: 3] of the matrix

>> M([1 3],[2:3])
ans =
2 3
8 9

The result is another 2x2 submatrix.

In this case the first parameter [1 3] is a list of single rows (the first row and the third row).

The second parameter [2: 3] is instead an interval between an initial and final column (from the second to the third column).

https://how.okpedia.org/en/matlab/how-to-extract-submatrices-from-a-matrix-in-matlab-and-octave

Report us an error or send a suggestion to improve this page

Matrix in Matlab/Octave