Extract rows from a matrix in Octave
In this lesson I'll explain how to extract the values of a single row or multiple rows from a two-dimensional array (matrix) in Octave.
I'll give you a practical example.
Create a matrix.
>> M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
M =
1 2 3
4 5 6
7 8 9
It is a 3x3 square matrix with three rows and three columns.
To extract the first row of the matrix type M(1,:)
- In the first parameter type 1 (first row of the matrix)
- In the second parameter type the colon symbol: (all columns of the matrix)
>> M(1,:)
This command allows you to extract all the values on the first row of the matrix
ans =
1 2 3
To extract the second row of the matrix type M(2,:)
Type 2 in the first parameter (second row of the matrix) and a colon symbol in the second parameter (all columns of the matrix)
>> M(2,:)
ans =
4 5 6
Finally, to extract the third row of the matrix type M(3,:)
The procedure is the same. In this case the command extracts only the third row of the matrix.
>> M(3,:)
ans =
7 8 9
If you want to extract only some columns of a row, specify the column range in the second parameter.
For example, to extract only the first two columns of the third row, type M(3,1:2)
>> M(3,1:2)
ans =
7 8
If the columns are not close to each other, type in the second parameter the list of columns to extract separated from each other by a comma or a space.
For example, to extract the first and third columns of the second row, type M(2,[1 3])
>> M(2,[1 3])
ans =
4 6
You can even extract multiple rows from the matrix at once.
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
In the first parameter there is the interval between lines 1:2 because the lines are contiguous
If you want to extract two separate rows from each other, type the column list in the first parameter.
The list of columns is in square brackets. The columns are separated from each other by a space or a comma.
For example, to extract the first and third rows of the matrix type M([1 3],:)
>> M([1 3],:)
ans =
1 2 3
7 8 9.
This way you can extract any row from a matrix in Octave.