
Extracting one or more rows from a matrix in Matlab
In this lesson, I will explain how to extract one or more rows from a matrix (two-dimensional array) in Matlab.
Here's an example.
Create a 3x3 matrix with three rows and three columns.
>> M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
M =
1 2 3
4 5 6
7 8 9
This is a square matrix because it has the same number of rows and columns, which is 3x3.
To extract the first row of the matrix, type M(1,:)
- The first parameter (1) indicates the first row of the matrix,
- The second parameter (:) is the colon symbol that means "take all columns of the matrix."
>> M(1,:)
This will extract all elements of the first row of the matrix.
ans =
1 2 3
Now, to extract the second row of the matrix, type M(2,:).
You need to specify 2 as the first parameter.
>> M(2,:)
ans =
4 5 6
This will extract the second row of the matrix.
Finally, to extract the third row of the matrix, type M(3,:)
This command will only extract the third row of the matrix.
>> M(3,:)
ans =
7 8 9
If you want to extract only some columns of a row, write the range of columns to consider in the second parameter.
For example, type M(3,1:2) to extract only the first two columns of the third row.
>> M(3,1:2)
ans =
7 8
When the columns to extract are not adjacent, indicate the list of columns within square brackets, separating them with a comma or a space.
For example, type M(2,[1 3]) to extract the first and third column of the second row.
>> M(2,[1 3])
ans =
4 6
To extract two or more rows from the matrix, write the list or range of rows to consider.
For example, to extract the first two rows of the matrix, type M[1:2,:]
>> M(1:2,:)
ans =
1 2 3
4 5 6
If you want to extract the first and third row of the matrix, type M([1 3],:)
>> M([1 3],:)
ans =
1 2 3
7 8 9.
This way, you can extract one or more rows from the matrix, even if they are not adjacent to each other.