lettura simple

Extract one or more columns from a matrix in Octave

In this lesson I'll explain how to extract a column or more columns 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.

an example of a matrix

To extract the first column of the matrix type M(:, 1)

  • In the first parameter type the colon symbol: to take all the rows of the matrix
  • In the second parameter type 1 to take only the first column of the matrix

>> M(:,1)

This command extracts all the values in the first column of the matrix

ans =
1
4
7

 

the first column of matrix

To extract the second column of the matrix type M(:, 2)

Leave the colon: in the first parameter and type 2 in the second parameter to get all the elements of the second column of the matrix.

>> M(:,2)
ans =
2
5
8

the second column of matrix

Finally, to extract the third column of the matrix type M(:, 3)

This will extract only the third column of the matrix.

>> M(:,3)
ans =
3
6
9

the third column of matrix

If you want to extract only some rows of a column, type the range of rows to consider in the first parameter.

For example, to extract only the first two rows of the third column, type M(1:2,3)

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

the first and second row of the third column

If the rows to be extracted are not close to each other, type the list of rows in square brackets in the second parameter, separating them from each other with a comma or a space.

For example, type M([1 3],2) to extract the first and third rows of the second column

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

 

the first and third row of the second column

You can also extract two or more columns from the matrix.

For example, type M(:, 1: 2) to extract the first two columns of the matrix

In the second parameter type the 1: 2 column range you want to take

>> M(:,1:2)
ans =
1 2
4 5
7 8

the first two rows of the matrix

To extract two or more columns separated from each other, type in the second parameter the list of columns to be extracted in square brackets separating them from each other with a space or a comma.

For example, type M(:, [1 3]) to extract the first and third columns of the matrix

>> M([1 3],:)
ans =
1 3
4 6
7 9

the first and third column of matrix

This way you can extract the columns of the matrix even if they are not close to each other.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin