How to | Get Parts of a Matrix
The Wolfram Language has many matrix operations that support operations such as building, computing, and visualizing matrices. It also has a rich language for picking out and extracting parts of matrices.
Define the following matrix. Note how a matrix in the Wolfram Language is not restricted to number entries:
mat = Table[Subscript[m, i, j], {i, 5}, {j, 5}];
mat//MatrixFormUse Part to go to the first row and take the second element:
Part[mat, 1, 2]Or use the shorthand notation [[…]] for Part:
mat[[1, 2]]To take an entire row, use one index to specify the row:
mat[[4]]To take an entire column, you need to select all rows with All and specify the column:
mat[[All, 4]]To pick out a submatrix, you can use Span (;;). First, define a 4×5 matrix:
mat = RandomInteger[10, {4, 5}];
mat//MatrixFormThe top-left 3×4 matrix with bold entries here corresponds to rows 1 through 3 and columns 1 through 4:
(| | | | | |
| - | -- | - | -- | - |
| 9 | 2 | 8 | 5 | 0 |
| 1 | 10 | 9 | 10 | 3 |
| 0 | 0 | 0 | 5 | 7 |
| 9 | 10 | 9 | 0 | 4 |)Extract the highlighted matrix by using Span (;;) to specify the relevant span of rows and columns:
mat[[1 ;; 3, 1 ;; 4]]mat[[1 ;; 3, 1 ;; 4]]//MatrixFormExtract all elements except the outermost rows and columns (negative indices count from the end):
mat[[2 ;; -2, 2 ;; -2]]mat[[2 ;; -2, 2 ;; -2]]//MatrixForm